3

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...

Xiiryo
  • 3,021
  • 5
  • 31
  • 48

2 Answers2

3

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>
  );
}
tigerpaw
  • 135
  • 4
1

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 atomFamilys that hold the content data of the posts.

Johannes Klauß
  • 10,676
  • 16
  • 68
  • 122