Recoil: Question: atomFamily and key.

Created on 28 May 2020  路  3Comments  路  Source: facebookexperimental/Recoil

Is there any way to get a element by key? How does the key applies on a atomFamily? Does atomFamily supports a dynamic list? Can I push and remove members of atomFamily at any given time?

Thank you.

question

All 3 comments

Hi @robsoncezario

Is there any way to get a element by key

This sounds like the same question as #181

How does the key applies on a atomFamily

I'm not sure exactly what you mean. But this is how the key in atomFamily is implemented:

https://github.com/facebookexperimental/Recoil/blob/5f4491a69b8d1e383e49ddae06a1d4f3ac14c8e2/src/recoil_values/Recoil_atomFamily.js#L236

Does atomFamily supports a dynamic list?
Can I push and remove members of atomFamily at any given time?

AtomFamily is a Map of the params passed to the function and the created atom. i.e. Map<params, Atom>.

const listItem = atomFamily({
  key: 'ListItem',
  default: null,
});

function MyComponent({list}) {
  const getValues = useRecoilCallback(({get}) => {
    return list.map(id => get(listItem(id)));
  }, [list]);

  ...
}

atomFamily is a factory pattern which will dynamically generate an atom based on the serialization of the parameters. You only need to provide a single key for the atomFamily, it will generate a key for each individual atom based on serializing the parameters. You can "add" an atom to an atomFamily simply by calling it with a new parameter value. The state for an atom in the family can be removed via useResetRecoilState() hook, though the key currently remains registered. We have plans to look at automatic memory management of unused atoms.

Improved docs with #186

Was this page helpful?
0 / 5 - 0 ratings

Related issues

eLeontev picture eLeontev  路  3Comments

jamiebuilds picture jamiebuilds  路  3Comments

yuantongkang picture yuantongkang  路  3Comments

adamkleingit picture adamkleingit  路  4Comments

art1373 picture art1373  路  4Comments