-
I have an async atom that I am initializing with a promise that returns an object. async function fakeAPICall() {
await new Promise((resolve) => setTimeout(resolve, 100));
return {
id1: { name: "john", age: 23 },
id2: { name: "bob", age: 45 },
id3: { name: "roger", age: 36 },
};
}
const queryAtom = atom(() => fakeAPICall());
const personAtom = (id: string) =>
atom(async (get) => (await get(queryAtom))[id]);
const Person = ({ id }: { id: string }) => {
const person = useAtomValue(personAtom(id));
return (
<Suspense fallback={<div>Loading...</div>}>
<div>{person.name}</div>
</Suspense>
);
};
export default function App() {
const people = useAtomValue(queryAtom);
return (
<Suspense fallback={<div>Loading...</div>}>
{Object.keys(people).map((person) => (
<Person id={person} />
))}
</Suspense>
);
} What's the correct way to handle this scenario? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
This causes infinite loop because it creates a new atom instance on every render. const person = useAtomValue(personAtom(id)); There are some approaches, one of which is atomFamily: const personAtom = atomFamily((id: string) =>
atom(async (get) => (await get(queryAtom))[id])); |
Beta Was this translation helpful? Give feedback.
This causes infinite loop because it creates a new atom instance on every render.
There are some approaches, one of which is atomFamily: