Reacotron's displaying actions before sagas - reactjs

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.

Related

Multiple parallels api call

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.

takeEvery and takeLatest. Why? When to use? Use simultaneously?

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.

Chain redux store update

I would like to dispatch an action after a first one has been processed by the reducers.
Here is my use case. My component allows the user to select a list of notes (this list is store in redux). Based on some user actions, a random note can be selected from this list and saved in the store.
In the screenshot you can see buttons. "Select All" and "Unselect All" act on the list of possible note. "Start" pick a note from the list.
The issue I have concern the "reset button". It is supposed to chain "select all" and "start" and I don't know how to do that. I tried a naive:
const reset = function () {
dispatch(selectAll());
dispatch(pickANote());
}
With this example, I am facing what I think is a data race. The second action pick a note from a note updated list.
Digging the internet, I found only cases of action chaining based on API calls with redux thunk. The problem I have is that I don't know how to trigger something when a action is processed (which is obvious with an API call)
So, there is 3 solutions:
I am missing something obvious
I am going where no man has gone before
I am doing something anti-pattern
Any help is welcome.
Alright, I found my answer.
No surprise, I was thinking anti-pattern.
In the redux style guide, there is 2 points that lead me to the solution.
It is strongly recommended to dispatch one action that is processed
by several reducers.
It is strongly recommended to put the logic inside the reducers.
The consequence is that I should dispatch "raw data" and then compute value reducers. Following this path, I am not dependent on the values already in the store for the next updates and so, I do not face any data race.

Problems with architecture of the redux store

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.

What does it mean for a Flux dispatcher to guarantee synchronous actions?

After having built a few apps using (what I believe) to be a Flux architecture based off a framework I built, I wonder what it means when:
Mozilla says:
"The dispatcher dispatches actions to interested stores. Only one
action can be processed at any one time."
Or Facebook says:
"We need the dispatcher to be able to invoke the callback for Store B,
and finish that callback, before moving forward with Store A."
Why I'm confused is because Javascript's concurrency model only allows one thing to happen at once, and ensures the call stack of the current action is depleted before it moves on with the task Queue.
So we get for free what Facebook and Mozilla says their dispatchers give us. We can't avoid it. Why are we talking about it like it's anything special?
Well... another consideration is if your "action" does something asynchronous with a callback like:
update state,
fire off an XHR,
update state with result.
Here your action can be broken in 2 parts and something can happen in between 2 and 3, thus violating the "one action at a time" principle.
That problem is solved by nothing more than terminology:
Define Action A as the thing that updates state and sends XHR.
result of XHR triggers Action B which updates state.
After all, Facebook has said "Actions may also come from other places, such as the server."
So with a little change in terminology we have no need for a dispatcher that does anything beyond dispatch an event to interested stores.
So what am I missing? Why must a dispatcher in Flux do anything more than dispatch?
My answer is: the people who wrote those bits of documentation weren't clear in what they were talking about.
Even the top stackoverflow React answerer and React contributor says:
In my understanding, asynchronous actions that rely on Ajax, etc.
shouldn't block the action from being dispatched to all subscribers.
You'll have a separate action for the user action, like
TODO_UPDATE_TEXT in the TodoMVC example and one that gets called when
the server returns, something like TODO_UPDATE_TEXT_COMPLETED (or
maybe just something more generic like TODO_UPDATE_COMPLETED that
contains a new copy of the latest attributes).
See: https://stackoverflow.com/a/23637463/131227

Resources