Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update redux state further down the tree

For a given reducer, my redux state tree typically looks something like this:

{
  someField: 'some value',
  // ... more fields
  metadata: {
    pending: false,
    fetched: true,
  }
}

Typically, when I do an async request, I fire a SOME_ACTION_REQUEST action, which sets the metadata.pending property to true. It's reset to false again when the matching SOME_ACTION_RESPONSE or SOME_ACTION_ERROR event trickles in later.

However, the way I update the state is a bit verbose:

case actions.SOME_ACTION_REQUEST: {
  return {
    ...state,
    metadata: { ...state.metadata, pending: true },
  };
}

Is there a simpler way of doing this?

Object.assign({}, state, { metadata: { pending: true } }) isn't very readable either.

like image 257
Kris Selbekk Avatar asked Oct 19 '22 01:10

Kris Selbekk


1 Answers

That's a pretty typical example of doing immutable data updates. You may want to read through the new Structuring Reducers section of the Redux docs for some further information, particularly the Prerequisite Concepts and Immutable Update Patterns pages.

like image 85
markerikson Avatar answered Oct 27 '22 11:10

markerikson