Ad

Redux: Accessing Current State - Best Practice?

Here is something I don't understand about Redux. I have an app which goes through items. You can go to the previous item and to the next item. As I understand it, you are not supposed to access the current state in your actions.

As regards my app, I have an array in my redux state which holds all the ids of my items: ["3123123123","1231414151","15315415", etc.] and I have a piece of state which holds the currently selected item (or better, it holds the id of that item). Now when the user clicks nextItem, I need to get the next item. My (unfinished) action look like this:

export function nextItem(currentId) {

  //my idea:
  //take the currentId, look where in the array it is, and get the position
  //increment that position
  //get the id of the next item in the array (at position: position+1)
  //update state

  return {
    type: SET_CURRENT_ITEM,
    payload: item
  }
}

Similar things would apply to the previous Item action creator. However, I am at loss how to implement this action creator, without accessing my current state? Where and how would that ideally happen?

Ad

Answer

I would suggest that you dispatch an action like:

{
    type: INCREMENT_CURRENT_ITEM
}

You can dispatch this from within any connected component directly:

dispatch({ type: INCREMENT_CURRENT_ITEM })

Or if you prefer to use an action creator, that's fine too:

dispatch(incrementItem()) // incrementItem() returns the action above

In your reducer, you have access to the current state, which is where you can increment the item index, without having to search for the current value in an array.

Ad
source: stackoverflow.com
Ad