0

I have an array of post objects that is stored in redux. I am mapping over the posts, and passing the ID and index to the Post component:

posts.map((post, index) => {
  <Post id={post.id} index={index} />
});

The redux style guide states:

Prefer having more UI components subscribed to the Redux store and reading data at a more granular level...

For example, rather than just connecting a <UserList> component and reading the entire array of users, have <UserList> retrieve a list of all user IDs, render list items as <UserListItem userId={userId}>, and have <UserListItem> be connected and extract its own user entry from the store.

However, I do not have a list of postIds, but I am still trying to get more components subscribed by mapping over the posts and passing a reference to the post component, instead of the post itself. (Is that a good idea?)

My question is regarding how I should read the post from the store. Whether by ID or by Index:

  1. post = state.posts.find(post => post.id === props.id)
  2. post = state.posts[props.index]

Obviously, reading by index will be much, much faster. But the posts array can be reordered. So I want to know if the index created by the map function is dependable?

1 Answer 1

1

The redux style guide is just a style guide. Even if they recommend to iterate over a list of id, if you have a list of component you can iterate over it.

The only "problem" here is that your application may become more and more complex over time, and it could be hard to maintain it later.

If you still want to find post by id, the find method is good, and should not be problematic if your don't have hundreds of items in your store.

If you want to do the second solution, you can transform your store in your reducer to something like this:

  function reducer(action, state) {
    switch (action.type) {
      case 'YOUR_CASE': {
        return {
          ...state,
-         itemList: action.itemList,
+         itemList: Object.fromEntries(
+           action.itemList.map(item => ([item.id, item]))
+         ),
        }
      }
    }
  } 

You will then have an object like this in your store:

{
  1: {
    id: 1,
    title: 'some item',
  },
  2: {
    id: 2,
    title: 'some other item',
  },
}

Watch out that Object.fromEntries is only a recent API, you might want to polyfill it.

You will of course need to change all call that used itemList as an array before like this:

- itemList: state.itemList,
+ itemList: Object.values(state.itemList),
Sign up to request clarification or add additional context in comments.

1 Comment

I think I have to edit my code a little bit to normalize the data. Thanks for the pointers!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.