Skip to main content
Module

x/jotai/docs/utils/abortable-atom.mdx

👻 Primitive and flexible state management for React
Go to Latest
File
---title: abortableAtom---
The `abortableAtom` utility is to define a derived atom with abortability.It uses [AbortController](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) so that you can abort async functions.Abort is triggered before new calculation (invoking `read` function) is started.
How to use it:
```tsconst readOnlyDerivedAtom = abortableAtom(async (get, { signal }) => { // use signal to abort your function})
const writableDerivedAtom = abortableAtom( async (get, { signal }) => { // use signal to abort your function }, (get, set, arg) => { // ... })```
The `signal` value is [AbortSignal](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal).You can check `signal.aborted` boolean value, or use `abort` event with `addEventListener`.
For `fetch` use case, we can simply pass `signal`.
See the below example for `fetch` usage.
## codesandbox
<CodeSandbox id="h1c9go" />```tsximport { Suspense } from 'react'import { atom, useAtom } from 'jotai'import { abortableAtom } from 'jotai/utils'
const userIdAtom = atom(1)const userAtom = abortableAtom(async (get, { signal }) => { const userId = get(userIdAtom) const response = await fetch( `https://jsonplaceholder.typicode.com/users/${userId}?_delay=2000`, { signal } ) return response.json()})
const Controls = () => { const [userId, setUserId] = useAtom(userIdAtom) return ( <div> User Id: {userId} <button onClick={() => setUserId((c) => c - 1)}>Prev</button> <button onClick={() => setUserId((c) => c + 1)}>Next</button> </div> )}
const UserName = () => { const [user] = useAtom(userAtom) return <div>User name: {user.name}</div>}
const App = () => ( <> <Controls /> <Suspense fallback="Loading..."> <UserName /> </Suspense> </>)
export default App```