Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jotai - Update a async loadable atom

Tags:

state

jotai

Current Code

const asyncAtom = atom(async () => {
  const res = await (
    await fetch("http://localhost:3000/api/transactions")
  ).json();
  return res;
 });

const loadableAtom = loadable(asyncAtom);
const [transactions] = useAtom(loadableAtom);

How can I update the transactions if I want to refetch the data?

With setTransactions I get the error "This expression is not callable. Type 'never' has no call signatures.ts(2349)".

like image 242
Snickers03 Avatar asked Aug 09 '26 09:08

Snickers03


2 Answers

The answer is to make the response the loadable atom and the request a setter atom, in your example:

const responseAsync = atom(null) 

const setAsyncAtom = atom(null, async (get, set) => {
  const res = (
    await fetch("http://localhost:3000/api/transactions")
  ).json();
  set(responseAsync, res)
 });

const loadableAtom = loadable(responseAsync);
const [transactions] = useAtom(loadableAtom);


...... (in component)

const [, refreshData] = useAtom(setAsyncAtom)


So you can call refreshData on demand when you need to refresh data.

like image 89
Fernando Catacora Avatar answered Aug 15 '26 12:08

Fernando Catacora


loadable(responseAsync) might not right, since loadable expect to receive async atom, otherwise loadableAtom wont have state of 'loading' | 'hasData' | 'hasError'. refer to https://jotai.org/docs/utilities/async

like image 41
Tianbo Avatar answered Aug 15 '26 12:08

Tianbo