Reputation: 3257
I'm testing Recoil and I need to manage a list of posts to display in the homepage.
My first idea was to make a big Atom with all the posts, but this seems a bit violent as we can edit posts directly on the homepage.
My second idea was to dynamically generate atoms with a prefix:
const onePost = (postId: string) => atom({
key: 'post_' + postId,
default: null,
effects_UNSTABLE: [localStorageEffect('@post_' + postId)],
});
Then I realized that I was pretty a rookie playing with fire and that I shall ask people who are knowledgeable about Recoil on StackOverflow...
Upvotes: 3
Views: 1700
Reputation: 145
You can use atomFamily to manage your posts. You can use another atom to manage the post ids, if you want to add and delete posts.
const postsFamily = atomFamily({
key: 'postsFamilyKey',
default: [0, 0],
});
function PostListItem({postID}) {
const post = useRecoilValue(postsFamily(postID));
return (
<div>
Post ID: {postID}
Post: {post}
</div>
);
}
Upvotes: 3
Reputation: 11020
You can just use an array:
const postIds = atom({
key: 'postIds',
default: [],
effects_UNSTABLE: [localStorageEffect('postIds')],
});
This way you manage the list of ids in one atom and those ids can refer to different atomFamily
s that hold the content data of the posts.
Upvotes: 1