Async Write Atoms

In Async write atoms the write function of atom returns a promise.

const counter = atom(0); const asyncAtom = atom(null, async (set, get) => { // await something set(counter, get(counter) + 1); });

Note: An important take here is that async write function does not trigger the Suspense.

But an interesting pattern that can be achieved with Jotai is switching from async to sync to trigger suspending when wanted.

const request = async () => fetch('https://...').then((res) => res.json()) const baseAtom = atom(0) const Component = () => { const [value, setValue] = useAtom(baseAtom) const handleClick = () => { setValue(request()) // Will suspend until request resolves } // ... }
import { atom, useAtom } from 'jotai';
import Suspense from './Suspense.js';

const counter = atom(1);

const asyncAtom = atom(null, async (get, set) => {
    await fetch('https://jsonplaceholder.typicode.com/todos/');
    set(counter, get(counter) + 1);
});

function AsyncComponent() {
  const [count] = useAtom(counter);
  const [, incCounter] = useAtom(asyncAtom);
  return (
    <div className="app">
      <h1>{count}</h1>
      <button onClick={incCounter}>inc</button>
    </div>
  )
}

export default function Page() {
   return (
    <div>
      <AsyncComponent />
      <Suspense />
    </div>
  )
}

Open on CodeSandbox