How to chain multiple data source loads that depends on each other?
See original GitHub issueHi,
Lets say I want to to make sure data source A, B and C are loaded to the redux store. Data source B is dependent on A and must be loaded after that A is loaded and data source C is dependent on data source B and must be loaded after B is loaded.
I also want to do this in a single function so I can do it in the same function scope.
How do I do this in a nice way in redux saga?
My take on this is the following:
...
export function* loadMultipleDataSources() {
// load data source A
yield put(document_actions.myDocumentsLoad());
yield take(
[
document_actions.MY_DOCUMENTS_LOAD_CACHED,
document_actions.MY_DOCUMENTS_LOAD_SUCCEEDED,
]
);
// load data source B, this must happend after 'MY_DOCUMENTS' are in the redux store
// load data source C...
export function* myDocumentsLoad() {
const my_documents = yield select(state => state.documents.get('all'));
if (my_documents.size > 0) {
yield put({
type: document_actions.MY_DOCUMENTS_LOAD_CACHED,
});
return;
}
...
However, this does not work because of how javascript works. The MY_DCOCUMENTS_LOAD_CACHED will trigger before the code in (1) has come to its take
.
However, if i tweak (2) a bit, by adding a delay
it works.
yield call(delay, 0); // needs to be here for take() to finish setup
yield put({
type: document_actions.MY_DOCUMENTS_LOAD_CACHED,
});
Now, the take
in (1) will finish up before the put
in (2).
Is this a good way to solve the problem? Is there some better solution to this problem?
Issue Analytics
- State:
- Created 7 years ago
- Comments:11 (6 by maintainers)
Top GitHub Comments
Ok. This might be in fact a little bit confusing - the ordering of things here. I would say the easiest and the most ‘clean’ way of handling this is using
channel
. You can do smth like that:It will buffer those actions internally in the created channel, so you wont miss them.
Do the actions you dispatch run sagas? If so then they aren’t all inside one function. It’s up to you how you want to organize your application, but one of the big benefits to sagas are their composability.