Reputation: 1597
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!
Upvotes: 4
Views: 691
Reputation: 159105
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]);
);
Upvotes: 6