I'm using redux-saga and redux libraries to handle my project in React.
I'll explain my issue: in one moment the frontend application will dispatch n multiple identical saga "CUSTOM_ACTION" action (expected behaviour). Now I'd like to have only one api calls even the actions are multiple. Take latest option doesn't work.
This my saga code:
function* testWorker() {
// call api only once
}
function* testWatcher() {
yield takeLatest("CUSTOM_ACTION", testWorker);
}
With this configuration I have n api calls, one for each action.
How can I solve my problem?
Thanks in advance to everyone who can help me
The answer kind of depends on what you mean by "in one moment".
If you mean that only one request should be running at a time, you can use the takeLeading effect instead of takeLatest. It will start the request for the first action dispatched an ignore all the others until the request saga is finished.
function* testWatcher() {
yield takeLeading("CUSTOM_ACTION", testWorker);
}
If you mean some specific time, you can use the debounce effect. It will run only a single saga for a given time (once the time is over, with the last action dispatched).
function* testWatcher() {
yield debounce(500, "CUSTOM_ACTION", testWorker);
}
You can run it with 0 for a very short amount of time.
There is also the throttle effect if you just want to limit the amount of requests created.
Related
I am not clear in when to use takeEvery and when to use takeLatest ? in redux-saga.
I got a basic difference by reading the official documentation. But what is the use of creating concurrent actions in takeEvery (for example, the user clicks on a Load User button 2 consecutive times at a rapid rate, the 2nd click will dispatch a USER_REQUESTED while the fetchUser fired on the first one hasn't yet terminated)
import { takeEvery } from `redux-saga/effects`
function* fetchUser(action) {
...
}
function* watchFetchUser() {
yield takeEvery('USER_REQUESTED', fetchUser)
}
Can anyone please explain. As I am completely new to redux-saga.
Thanks in advance.
Though #Martin Kadlec's solid answers covers the question, I want to elaborate a bit more on the details and differences on takeEvery and takeLatest and when they might be used so you can derive the possible use-cases of them.
TLDR:
You can use takeEvery when the returns of all previous tasks are needed. For example fetching temperature and humidity data from a weatherstation over a certain period to be stored in a database and displayed as a graph - in this case all previous sagas and their return-values are of interset and not only the latest.
You can use takeLatest if i.E. a internal/external instance or a user of an interface could trigger multiple consecutive actions and only the conclusion of the last value is desireable. A good example would be rapid calls to a broker-API for a live-ticker for stock-values where only the latest/most recent value is of interest.
DETAILED:
Think of takeEvery and takeLatest as helper funtions on top of the lower level API of redux-saga which are wrapping internal operations such as spawning tasks when specific actions are dispatched to the Store. Calling them spawns a saga on each action dispatched to the Store that matches pattern.
takeEvery:
The most common takeEvery function is very similar to redux-thunk in its behaviour and methodology. It's basically a wrapper for yield take of a pattern or channel and yield fork.
The clue about takeEvery is that it allows multiple instances of a defined action/task (such as fetchSomeThing in the example below) to be started concurrently/simultaniously.
Unlike takeLatest you can start a new fetchSomeThing task while one or more previous instances of fetchSomeThing have not yet been completed/terminated, therefore are still pending. Keep in mind that there is no guarantee that the tasks will terminate/complete in the same order they were started. To handle out of order responses, you could use takeLatest.
From the official docs:
takeEvery(pattern, saga, ...args)
Spawns a saga on each action dispatched to the Store that matches pattern.
pattern: String | Array | Function
saga: Function - a Generator function
args: Array - arguments to be passed to the started task. takeEvery will add the incoming action to the argument list (i.e. the action will be the last argument provided to saga)
You can also pass in a channel as argument instead of a pattern resulting in the same behaviour as takeEvery(pattern, saga, ...args).
takeLatest:
The takeLatest helper function in contrast only gets the response of the latest request that was fired and can be seen as a wrapper for yield take of a pattern or channel and an additional if-statement checking if a lastTask is present (a previous task that is still pending), which will then be terminated via a yield cancel and a subsequent yield fork that will spawn the current task/action.
From the official docs:
takeLatest(pattern, saga, ...args)
Will only get the response of the latest request fired.
pattern: String | Array | Function
saga: Function - a Generator function
args: Array - arguments to be passed to the started task. takeLatest will add the incoming action to the argument list (i.e. the action will be the last argument provided to saga)
Similar to takeEvery you can also pass in a channel as argument instead of a pattern.
This is something you really need to think about per use case.
These are some cases when you might use takeEvery.
For sagas that are not asynchronous and so there is no reason to
cancel them. takeLatest would work here as well but it might give
false indication when reading code that there is something to
cancel.
Sometimes when the action differs in some way each time. E.g.
imagine you have a movie and you are adding tags with genre of the
movie. Each time the action is triggered you get a different genre,
even though it is the same action type. The user can add genres
quicker than you get response from the server. But just because you
added multiple genres quickly doesn't mean you want to stop the saga
adding the previous one.
Cheap implementation of when you have the same load action for
multiple different items. E.g. You have list of movies and each has
"load detail" button. (Let's ignore the fact that you should
probably hide or disable the button once the loading starts). The
data are always the same for one movie but differs in between them.
When you click on load detail for movie 1 you don't want to cancel
loading of data for movie 2. Since it is a dynamic list of movies
the action type is the same every time, the difference will be
probably something like id of the movie in the action.
In ideal implementation you should probably cancel the previous load saga for
the same movie/id, but that will require more complicated code and
so if you are doing only some simple app you might decide to ignore
that and just allow to run the sagas for same movie multiple times.
That is why I call it "cheap implementation".
To summarize in a few words,
takeEvery allows concurrent actions to be handled. For example, the user clicks on a Load User button 2 consecutive times at a rapid rate, the 2nd click will dispatch a USER_REQUESTED action while the fetchUser fired on the first one hasn't yet terminated.
takeEvery doesn't handle out of order responses from tasks. There is no guarantee that the tasks will terminate in the same order they were started. To handle out of order responses, you may consider takeLatest.
takeLatest instead start a new fetchUser task on each dispatched USER_REQUESTED action. Since takeLatest cancels any pending task started previously, we ensure that if a user triggers multiple consecutive USER_REQUESTED actions rapidly, we'll only conclude with the latest action
Docu: https://redux-saga.js.org/docs/api/
takeEvery - enables the use of several fetchData objects at the same time.
At a given moment, we can start a new fetchData task while there
are still one or more previous fetchData tasks which have not
yet terminated.
takeLatest - Only one fetchData task can be active at any given moment. It
will also be the work that was started most recently. If a new
fetchData job is started while a previous task is still running,
the previous work will be terminated immediately.
I just downloaded Reactotron, but found a pretty strange error(?).
To be able to understand it I will describe my process flow:
1.) App is starting
2.) I dispatch a ON_START_APP
3.) I will takeEvery ON_START_APP in a saga
4.) ON_START_APP will put (saga) a START_FETCH_RATES
5.) START_FETCH_RATES will put a FETCH_RATES_FAIL
But for some reason the ACTION is displayed before the SAGA is PUTTING IT IN.
Quite strange, right?
Is this how it's should work?
It is the expected behavior. Reactotron displays saga information once the forked task is completed. Since your put effect is executed before the the saga is actually complete, you should see the action before you see saga details.
Where should you put the API-calls in Redux?
I think they belong in Actions because they are part of the data and don't have side-effects.
Does that sound right?
I want to avoid RxJS or ReduxSaga.
I make my API calls in my action file but have a separate function that creates the action itself. Regardless I am agreeing with you in that API Calls work best (in our collective opinion) alongside action creators.
Create Scenarios
If you call a synchronous API just in a single component, you can make your API call in actions, get the data back, and then dispatch. Simple is that.
If you call a synchronous API in multiple components, You will handle them all separately?
If you call a asynchronous API, You will dispatch a flag when the request began and again dispatch a flag when request complete?
For point 2,3 Thunk middleware is the best option as it is much easier than Saga.
This is a can of worms in the redux world and there are many approaches. The main idea is to execute functions that have access to the store’s dispatch method so that these functions can orchestrate their own sequence of actions to the store. However, each approach dresses up the function execution and the inherent statefulness of side effects (e.g. waiting for an API call to finish before dispatching the “done” action to the store) in a different way:
The imperative solution is thunks which are just plain old functions. When the store receives a thunk, instead of running the thunk through the reducer like a regular object action, the store executes the thunk while passing the store’s dispatch function so that the thunk can orchestrate its own sequence of actions. See redux-thunk for an example.
redux-saga is a declarative solution where you dispatch action objects that describe how the side effect is to be carried out. For example, if the side effect is fetching from an API then the action contains the fetch function and the arguments to be passed to the fetch function. For example, if the fetch call is fetchFromServer(a, b, c) then the action you dispatch contains fetchFromServer, a, b and c. The stateful part of the side effects is kept inside generator functions called “sagas”.
redux-observable is another declarative solution but instead of using generators for “statefulness”, it uses observables. Observables can be a bit non-intuitive so I won’t go much into it here but it is the solution that I used. Honestly, the latter two are, to some extent, two sides of the same coin but I find observables a more elegant abstraction.
I'm developing an application that has several states (reducers). Let's say they are messages, likes, comments (all of them are from the completely different instances so i'm not sure if i should combine them into one state).
Every 30 seconds i make request to the server and i receive response that says which parts of my application have been updated. E.g. i received new messages or new comment.
I don't really know how to handle those responses. First, i can simply let container update all other states, but i don't think that it's a good idea, because every container should have it's own state.
Second, i can create a middleware that will catch every action, find the one with required information and shot another action (e.g. new message). After that reducer of the messages will catch this action. But i'm not sure again if this is a correct approach for two reasons:
Is it okay to shot actions from the middleware (won't it be a bidirectional flow)?
How can i actually do it?
Thanks in advance.
UPD. I did it using middleware, but i'm still not sure if this is a correct way. In my middleware i obtain required data using store.getState()... and then i make store.dispatch(myAction). Is it okay?
It's important to understand that a reducer /= state. ( reducer not equal state )
You should have one state, one store for your application. Use combineReducers to well.. combine reducers to keep everything in one state.
http://redux.js.org/docs/api/combineReducers.html
You need to handle async behaviour, something which is not default by redux and therefore you have to use some kind of middleware - meaning you were on the right track.
Try and use the more common once like:
https://github.com/gaearon/redux-thunk
https://github.com/redux-saga/redux-saga
It's advised to separate the async logic from your app. Meaning you need to init your async calling in the app, but keep the async logic in the store.
Here's a guide by Dan Abramov and Redux-Thunk which is simple and clear:
http://redux.js.org/docs/advanced/AsyncActions.html
Hope it answers you.
I think there are three options:
The UI Component calls two ActionCreator methods. Each ActionCreator dispatches a message.
The UI Component calls one ActionCreator method which dispatches a message and calls another ActionCreator method.
The UI Component calls one ActionCreator method which does not dispatch any message, but calls two other ActionCreator methods which each dispatch their own message.
Is there a reason to prefer one of these options over the others? Is there any other option?
This is setter-thinking, and is not the correct way to be thinking about Actions. Actions inform your application, they do not cause side effects.
Stores are in control of your application. They are where all logic resides. Stores cause side effects in response to the information they receive from actions. Actions are like a newspaper. Stores respond to the news.
Actions describe something that happened in the real world. In this case, the user did something. It could instead be that the server responded with some data, or that the browser completed an animation frame. Regardless, it is a singular event that actually happened, not an artificial construct of the code.
What you want here instead is to respond in two different ways to this user event, this single action. Two different stores will respond to the same action, but in different ways.
So you would have this in the event handler:
MyAppActions.userClicked(itemID);
and that would create an action like this:
userClicked: function(itemID) {
MyDispatcher.dispatch({
type: MyAppActions.types.USER_CLICKED,
id: itemID,
});
},
and that would play out in your stores like:
switch (action.type) {
case MyAppActions.types.USER_CLICKED:
this._handleUserClicked(action.id);
break;
// ...
}
In the two stores, the implementation of _handleUserClicked would do things specific to the particular store.
There's no reason to prefer one over another, Eric -- unless you need them to be done in a specific order. If that's the case, you probably want to have the First Action do its thing then call the Second Action (which you identified in No. 2 above). But if there's no ordering, there's no particular reason to prefer any of the three methods you outlined.
Like Hal stated, it depends on what you're using them for.
The UI Component calls two ActionCreator methods. Each ActionCreator dispatches a message.
I think this is the best solution if you're not specifically sure what you'll use the actions for. If there's any chance the methods could be called individually in other circumstances, it will be easier if you have the UI component call two ActionCreator methods.
The UI Component calls one ActionCreator method which dispatches a message and calls another ActionCreator method.
It's a good point that if you need actions to be done in a certain order, you should have one action that calls another to be sure that the first action completes before the second one begins.
The UI Component calls one ActionCreator method which does not dispatch any message, but calls two other ActionCreator methods which each dispatch their own message.
I think this is probably the least useful because it does the same thing as situation 1 but forceably binds those two actions together. Only use this if you'll always need both actions to be executed.