As I understand it, action creators have no view of the state, and reducers are not allowed to trigger new actions. So how do you condition an action based on the state - does that need to be done in the render function?
As an example, I have a component that lists titles to the set of items. This data is stored in state.matches
. Clicking on an item should bring up a detailed view in my Entries
component.
At present, I have this action creator that downloads the entry and triggers an action addEntry
which causes the entries
reducer to add the data to the cache in state.entries.
export function getEntryFromId(id) {
return function(dispatch) {
dispatch(lookupInit(id));
fetch('/register/id/' + id)
.then( res => res.json() )
.then( res => dispatch(addEntry(res[0])) ) // data returned as array of one element
.catch( err => dispatch({ type: ENTRY_LOOKUP_FAIL }) );
}
}
At present it always downloads new data as it cannot check the cache.
An alternative would simply be to pass the id
as SHOW_THIS_NEXT action to the entries side, at which point the reducer could check whether it is in the cache and download it if not. But reducers are not allowed to trigger actions and may ultimately be forbidden.
How do I square this circle.
I assume you're using Redux Thunk to handle returning the thunk from getEntryFromId
? The function you return can take a getState
argument:
export function getEntryFromId(id) {
return function(dispatch, getState) {
const currentState = getState();
// do something with `currentState`,
// only dispatch if necessary
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With