Redux users: how to easily update deeply nested store value


(Artem Kuzko) #1

Hey guys!

If you use vanilla redux in your app and ever got tired writing structures like

// for instance, activating company by given action.id
return {
  ...state,
  companies: {
    ...state.companies,
    list: state.companies.list.map((company) => {
      return company.id === action.id ? { ...company, active: true } : company
    })
  }
};

then there is a package called update-js that you might find useful. With update-js example above looks like following:

return update(state, `companies.list.{id:${action.id}}.active`, true);

I understand there are things like React’s Immutability Helpers and immutable-js, but if you don’t want to have additional data abstraction layer and just want simple helpers with, basically, no special API, update-js might serve you well.

Any comments and feedback are very welcome.

Thanks and happy coding!


(David Lormor) #2

We typically use lodash in our projects, and use the fp/set to perform similar functionality. get is another great function for referencing deeply nested entities that may or may not exist, while providing default values as well.