Thursday, February 9, 2023

Fetch calls with global Jotai object

Zustand is a great React state management library, but it has the drawback of not having a standard way to define getters, which must be defined as ordinary hooks.

Written by the same author, Jotai seems to be the answer to this situation. However, while Zustand provides a way to change the state outside React components, Jotai does not. Today I was able to devise a way to work around this, by simply applying the hooks concept, answering my own question:

const errorAtom = atom(''); // storage

const errorReadAtom = atom(get => { // read-only (computed)
	return 'Error: ' + get(errorAtom);
});

const writeErrorAtom = atom(null, (get, set, arg: string): void => { // setter
	set(errorAtom, arg);
});

function useGet(): (url: string) => Promise {
	const [, setError] = useAtom(errorAtom);
	return async (url: string): Promise => {
		const resp = await fetch(url);
		const json = await resp.json();
		setError('Hello');
		return json as T;
	};
}

Usage:

function App() {
	const doGet = useGet();

	async function click(): void {
		const data = await doGet('/foo');
	}

	return <button onClick={click}>Click</button>;
}

So, with Jotai I finally have the complete solution to state management in React.