Jotai - Update a async loadable atom
Asked Answered
G

2

7

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

Gaillardia answered 19/11, 2022 at 14:29 Comment(0)
A
3

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.

Aigneis answered 23/5, 2023 at 21:12 Comment(0)
E
1

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

Endocarp answered 26/3, 2024 at 22:42 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.