You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Generators can pause and restart — be exited and re-entered — and actually remember the context/state of the function over time.
Each yield in a generator basically represents an asynchronous step in a more synchronous/sequential process — somewhat like await in an async function.
```javascript
// rootSaga.js
import { takeLatest, call, put } from"redux-saga/effects";
nikneroz
revised
this gist Mar 30, 2018.
1 changed file
with
14 additions
and
9 deletions.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- Руководство для начинающих - https://redux-saga.js.org/docs/introduction/BeginnerTutorial.html
- API - https://redux-saga.js.org/docs/api/
- Статья - https://hackernoon.com/redux-saga-tutorial-for-beginners-and-dog-lovers-aa69a17db645
```
API_CALL_REQUEST says that we’re beginning the process of fetching a dog from the Dog API.
API_CALL_SUCCESS tells the Store that we successfully retrieved a dog and are therefore no longer in the process of fetching one.
API_CALL_FAILURE tells the Store that something went wrong with our API call. We received an error rather than a new dog
API_CALL_REQUEST описывает что мы начинаем процесс получения данных с API
API_CALL_SUCCESS описывает что store успешно получил данные и процесс получения данных завершен
API_CALL_FAILURE описывает что API вызов завершился ошибкой
```
-a watcherSaga is a saga that watches for an action to be dispatched to the Store, triggering a workerSaga.
- takeLatest is a helper function provided by redux-saga that will trigger a new workerSaga when it sees an API_CALL_REQUEST, while cancelling any previously triggered workerSaga still in process to help avoid too frequent or unnecessary API calls.
- fetchDog simply uses axios to request a random dog image from the Dog API and returns a Promise for the response.
- workerSaga attempts to fetchDog, using another redux-saga helper function call, and stores the result (a resolved or failed Promise) in a response variable.
-If fetchDog was a success, we extract the dog image from the response and dispatch an API_CALL_SUCCESS action with dog in the payload to the Store, using ANOTHER redux-saga helper function put.
-If there was an error with fetchDog, we let the Store know about it by dispatching an API_CALL_FAILURE action with the error.
-`watcherSaga` - это сага, которая следит за тем, чтобы экшен был отправлен в store, вызывая `workerSaga`.
-`takeLatest` - это вспомогательная функция, предоставляемая redux-saga, которая будет запускать новую `workerSaga`, когда она получит `API_CALL_REQUEST`. В то же время отменяет ранее запущенную `workerSaga`, для отмены слишком частых или ненужных вызовов API.
-`fetchDog` просто использует axios для запроса случайного изображения собаки из API и возвращает Promise для ответа.
-`workerSaga` вызывает функцию `fetchDog`, используя другой вызов helper function redux-saga и сохраняет результат (из promise) в переменной ответа.
-Если `fetchDog` был успешным, мы получаем изображение собаки из ответа и отправляем действие API_CALL_SUCCESS с payload в store, используя соответсвующий экшн redux-saga.
-Если произошла ошибка в `fetchDog`, мы сообщим об этом Store, отправив действие API_CALL_FAILURE.
Generators can pause and restart — be exited and re-entered — and actually remember the context/state of the function over time.
Each yield in a generator basically represents an asynchronous step in a more synchronous/sequential process — somewhat like await in an async function.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
API_CALL_REQUEST says that we’re beginning the process of fetching a dog from the Dog API.
API_CALL_SUCCESS tells the Store that we successfully retrieved a dog and are therefore no longer in the process of fetching one.
API_CALL_FAILURE tells the Store that something went wrong with our API call. We received an error rather than a new dog
```
- a watcherSaga is a saga that watches for an action to be dispatched to the Store, triggering a workerSaga.
- takeLatest is a helper function provided by redux-saga that will trigger a new workerSaga when it sees an API_CALL_REQUEST, while cancelling any previously triggered workerSaga still in process to help avoid too frequent or unnecessary API calls.
- fetchDog simply uses axios to request a random dog image from the Dog API and returns a Promise for the response.
- workerSaga attempts to fetchDog, using another redux-saga helper function call, and stores the result (a resolved or failed Promise) in a response variable.
- If fetchDog was a success, we extract the dog image from the response and dispatch an API_CALL_SUCCESS action with dog in the payload to the Store, using ANOTHER redux-saga helper function put.
- If there was an error with fetchDog, we let the Store know about it by dispatching an API_CALL_FAILURE action with the error.
Generators can pause and restart — be exited and re-entered — and actually remember the context/state of the function over time.
Each yield in a generator basically represents an asynchronous step in a more synchronous/sequential process — somewhat like await in an async function.
```javascript
// rootSaga.js
import { takeLatest, call, put } from"redux-saga/effects";
importaxiosfrom"axios";
// watcher saga: watches for actions dispatched to the store, starts worker saga
exportfunction*watcherSaga() {
yieldtakeLatest("API_CALL_REQUEST", workerSaga);
}
// function that makes the api request and returns a Promise for response
functionfetchDog() {
returnaxios({
method:"get",
url:"https://dog.ceo/api/breeds/image/random"
});
}
// worker saga: makes the api call when watcher saga sees the action
function*workerSaga() {
try {
constresponse=yieldcall(fetchDog);
constdog=response.data.message;
// dispatch a success action to the store with the new dog
yieldput({ type:"API_CALL_SUCCESS", dog });
} catch (error) {
// dispatch a failure action to the store with the error