R. Kohlisch
R. Kohlisch

Reputation: 2993

How to keep order in Redux state?

I have read that it's not advisable use an array as the state object in Redux. So one should not have state = [ {}, {}, {} ] but instead state={ "id1": {}, "id2": {}, "id3": {} }.

I have an API endpoint which returns an array of users. I mostly want to display each user in exactly the order it appears in in the array.

In a use case like this, is it still not advisable to save this as an array in state? The problem seems to be that I will need to show the users in the particular order, but I do also sometimes need to access users by id, so I am confused what a common strategy would be here to (1) keep the order and (2) access each object in a fast and efficient way (by id)?

edit: I am using mongodb id's for each user object, so id's and order does not simply match up. So it's not like object no. 1 (in terms of order) also has id 1. (although I could of course ignore mongos id's and implement my own, if that's good practice)

Upvotes: 3

Views: 1882

Answers (1)

Chaim Friedman
Chaim Friedman

Reputation: 6253

A strategy my team uses is to have state look something like this

const state = {
  byID: {
    id: Object
  },
  ids: ["1", "2"...] // array of ids 
}

In order to display the data, we have a list component which subscribes to the array of ids and iterates through them. We then have the single item component which gets rendered for each item in the id array, it accepts the id as a prop from the list, and it also subscribes to the byID object. It then uses the id getting passed in to retrieve the exact item out of the byID object to render.

This way order will stay in tact, while still giving you all the benefits of having your state stored in an object vs an array.

Example of the single item component.

class Person extends React.Component {
  render() {
    return (
      <div>
        <span>{this.props.person.firstName}</span>
      </div>
    );
  }
}

function mapStateToProps(state, ownProps) {
  return {
    person: state.people.byID[ownProps.id]
  }
}

Upvotes: 5

Related Questions