Replies: 1 comment 6 replies
-
Hey @devnomic, yes, it sounds like the second approach is what you want in this case. This takes advantage of automatic caching - each atom instance holds a cached query result. You can then control the lifetime of these caches with TTL. For example: const userProfileAtom = atom("userProfile", (userId: number) => {
const url = `https://jsonplaceholder.typicode.com/users/${userId}`;
const promise = fetch(url).then((result) => result.json());
return api(promise);
}, { ttl: 60000 }); // keep unused users in memory for 1 minute Ions take params too btw, after the first AtomGetters argument const exampleIon = ion('example', ({ get }, myParam: string) => ...) Without params, the atom is a singleton - only one atom instance is ever created. If you need more control over the cache, a singleton gives you that, but you'd have to implement all the caching logic manually. I've never needed this. If you don't want to have to pass params every time, you can create a selector that does it for you: const getUserProfile = ({ get }: AtomGetters) => get(userProfileAtom, [get(userIdAtom)])
// then in a component:
const { data } = useAtomSelector(getUserProfile) I use this all the time, but (very important) note that |
Beta Was this translation helpful? Give feedback.
-
Hi,
I am trying to derive atom using ion like this.
While this works, it always trigger suspense when fetching user profile.
https://codesandbox.io/s/zedux-ion-s6w4w0?file=/src/App.tsx
If i'm using normal atom with param, this works as intended / the results are cached.
https://codesandbox.io/s/zedux-ion-2-utxibv?file=/src/App.tsx
Is it possible to achieve same result using ion?
Or is it generally better to use the second approach (atom with params) when using zedux?
Thank you
Beta Was this translation helpful? Give feedback.
All reactions