Global read/write store for React using jotai
2022-09-19T02:34:21.779
I've been using jotai to manage the global state for my recent (and ongoing) refactor of Offworld. I kind of love jotai's simple and composable building blocks. I haven't used svelte yet, but if I recall from reading the docs correctly, it is somewhat similar to the svelte/store.
Here is a little example for creating a getter and setter (which is an async function using another function to find a user). The setter takes up to 3 arguments: a get function (for reading atoms within your setter callback), a set function (for actually changing state), and a value which is passed when the setter is called. In this example, the setter is called without any arguments so we leave out the value argument.
const userAtomPrimitive = atom(undefined);
export const userAtom = atom(
(get) => get(userAtomPrimitive),
async (_, set) => {
const user = await findUser();
set(userAtomPrimitive, user);
}
);