Search code examples
reactjsrecoiljs

How to get all elements from an atomFamily in recoil?


Im playing around with recoil for the first time and cant figure out how I can read all elements from an atomFamily. Let's say I have an app where a user can add meals:

export const meals = atomFamily({
  key: "meals",
  default: {}
});

And I can initialize a meal as follows:

const [meal, setMeal] = useRecoilState(meals("bananas"));
const bananas = setMeal({name: "bananas", price: 5});

How can I read all items which have been added to this atomFamily?


Solution

  • You have to track all ids of the atomFamily to get all members of the family. Keep in mind that this is not really a list, more like a map.

    Something like this should get you going.

    // atomFamily
    const meals = atomFamily({
      key: "meals",
      default: {}
    });
    
    const mealIds = atom({
      key: "mealsIds",
      default: []
    });
    

    When creating a new objects inside the family you also have to update the mealIds atom.

    I usually use a useRecoilCallback hook to sync this together

      const createMeal = useRecoilCallback(({ set }) => (mealId, price) => {
        set(mealIds, currVal => [...currVal, mealId]);
        set(meals(mealId), {name: mealId, price});
      }, []);
    

    This way you can create a meal by calling:

    createMeal("bananas", 5);
    

    And get all ids via:

    const ids = useRecoilValue(mealIds);