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)".
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With