JotaiJotai

状態
Primitive and flexible state management for React

abortableAtom

The abortableAtom utility is to define a derived atom with abortability. It uses AbortController so that you can abort async functions. Abort is triggered before new calculation (invoking read function) is started.

How to use it:

const 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. 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

import { 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