Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redux: conditioning action on state

Tags:

reactjs

redux

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.

like image 754
Simon H Avatar asked Oct 24 '15 19:10

Simon H


1 Answers

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
  }
}
like image 59
Michelle Tilley Avatar answered Sep 23 '22 10:09

Michelle Tilley