I'm having a bit of trouble figuring out what I think is a pretty common use case for Redux. I have a particular data domain, which is being populated from two different API endpoints. I need to wait until both calls return and all data is put into the store before I'm ready for reselect to do it's thing. As it is now, because mapStateToProps is called every time the state changes (i.e. on the initial render, after the first call, after the second call, etc), my selectors are bombing because the data isn't there.
What is the best approach for this? Do I have a parent component that's sole function is to check whether my isXFetched flags are all set, and only then render my connected component that uses reselect? There must be a better way I'm not thinking about, any ideas?
Here's a simplified example of my current implementation:
stores/indices.js
const initialState = Immutable.from({
areAllIndicesFetched: false,
areCurrentIndexAssetsFetched: false,
byId: {},
allIds: [],
});
...
'INDICES/FETCH_ALL_SUCCESS': (state, action) => {
// (other logic)
return state.merge([{
byId,
allIds,
areAllIndicesFetched: true,
}]);
}
'INDICES/FETCH_ASSETS_SUCCESS': (state, action) => {
// (other logic)
return state
.setIn(['byId', id, 'assets'], assets)
.set('areCurrentIndexAssetsFetched', true);
}
selectors.js
// This depends on the first call having succeeded
export const getIndexById = (state, props) => {
return state.byId[props.indexId];
}
// This depends on both the first and second call succeeding
export const getIndexAssets = createSelector(
getIndexById,
(index) => {
return index.assets;
}
);
Selectors are meant to be synchronous. Like with React components re-rendering, you need to handle the cases where data is not yet available (similar to the article Watch Out for Undefined State).
So, I would suggest having your selectors either return default values if the data they are looking for doesn't exist, or do existence checks and return null (and also handle that safely along the way).
That all makes sense, it seems easiest/more-encapsulated to have a short-circuit on the selectors to return an empty data structure of the appropriate type, or whatever would make sense as a default, thanks 馃憤
Most helpful comment
Selectors are meant to be synchronous. Like with React components re-rendering, you need to handle the cases where data is not yet available (similar to the article Watch Out for Undefined State).
So, I would suggest having your selectors either return default values if the data they are looking for doesn't exist, or do existence checks and return
null(and also handle that safely along the way).