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.
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".