4

I am wondering what design would be best for this. I have a list that is fetched remotely. Let's say it's a list of posts.

posts  {
    1: { title: 'some title', body: 'some body'},
    2: { title: 'another title', body: 'another body'}
}

In this list a user can select each post for an action (and even batch actions). Let's say that in the UI each small post will have a checkbox.

So, the backend doesn't care about these select actions, but I need to know exactly which posts are selected (for deletion for example) so that the front end can send a request to the backend. One way to handle that is to have the shape of the state look like this:

{
    posts  {
        1: { title: 'some title', body: 'some body'},
        2: { title: 'another title', body: 'another body'}
    }
    selectedPosts: [1, 2]
}

But that might make rendering complicated in the UI.

Then the alternative is to directly modify the data for each post when the post is selected. Like this:

{
    posts  {
        1: { title: 'some title', body: 'some body', selected: true},
        2: { title: 'another title', body: 'another body'}
    }
}

But this seems antithetical to how react & redux are intended to be used. Any feedback is appreciated!

1 Answer 1

6

I'd go with the former approach, and write any sort of helpers you need to massage the data into what you need. For example, a simple map could get all the selected posts:

const selectedPosts = state.selectedPosts.map(id => state.posts[id]);

You'd use something like this in your connect function, or use something like reselect:

import { createSelector } from 'reselect';

const postsSelector = state => state.posts;
const selectedPostIdsSelector = state => state.selectedPosts;

const selectedPostsSelector = createSelector(
  postsSelector ,
  selectedPostIdsSelector ,
  (posts, selectedPosts) => selectedPosts.map(id => posts[id]);
);
Sign up to request clarification or add additional context in comments.

3 Comments

Good answer, but the reselect api is hard to digest.
Thanks for the confirmation!
@RickJolly You don't have to use Reselect API to write functions that take the state and return a state-ready-for-UI-components. See Redux example in Flux Comparison for selectors that don't even use Reselect.

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.