Snickers03
Snickers03

Reputation: 71

Jotai - Update a async loadable atom

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)".

Upvotes: 7

Views: 2512

Answers (2)

Tianbo
Tianbo

Reputation: 77

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

Upvotes: 1

Fernando Catacora
Fernando Catacora

Reputation: 51

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.

Upvotes: 3

Related Questions