jotai: [Question] Learning why derived setter is not causing suspend (add docs that only direct atom's suspend on write)
Doing set from the dervied atom on an async child atom, is not causing the “Loading…” fallback of the <Suspend>
to show.
const [enabled, toggleEnabled] = useAtom(toggleEnabledAtom);
toggleEnable();
However doing it on the async child atom itself does show the fallback “Loading…”:
const [enabled, setEnabled] = useAtom(enabledAtom);
setEnabled(true);
Below is playground. Can you please help me understand this?
Playground - https://codesandbox.io/s/jotai-playground-uuyd5?file=/src/App.js:0-1342
import { atom, Provider, useAtom } from "jotai";
import React, { Suspense } from "react";
const enabledAtom = atom("init", async (_get, set, nextValue) => {
await new Promise((resolve) => setTimeout(resolve, 1000));
set(enabledAtom, nextValue);
});
const toggleEnabledAtom = atom(
(get) => get(enabledAtom),
async (get, set) => {
const enabled = get(enabledAtom);
if (enabled) {
await set(enabledAtom, false);
} else {
await set(enabledAtom, true);
}
}
);
function Atomed() {
const [enabled, toggleEnabled] = useAtom(toggleEnabledAtom);
return (
<>
<div>{String(enabled)}</div>
<div>
<button
type="button"
onClick={() => {
toggleEnabled();
}}
>
{enabled ? "Disable" : "Enable"}
</button>
</div>
</>
);
}
export default function App() {
return (
<Provider>
<div className="App">
<Suspense fallback="Loading...">
<Atomed />
</Suspense>
</div>
</Provider>
);
}
About this issue
- Original URL
- State: closed
- Created 3 years ago
- Comments: 19 (8 by maintainers)
PR opened thanks to @angusryer’s notes - https://github.com/JLarky/jotai/pull/1
@angusryer Thanks for the summary! Please do note this is about async
write
. In the readme, it’s called “Async actions”. We also have asyncread
, which is “Derived async atoms” in the readme, and for this, all atoms having values (and their derived) will suspend.