Fetch remote state
A component needs current server data such as a count or list.
Zustand · Const
Zustand actions can be asynchronous: fetch remote data, await its typed response, and update store state with set. No special middleware is required for the documented pattern.
An async action is a store method declared with async and returning a promise. It performs the request, awaits the response and parsed data, then calls set with the resulting state update; Zustand does not require special async handling.
fetchBears: () => Promise<void>fetchBears returns Promise<void>.
import { create } from 'zustand'
type BearData = { count: number }
type BearState = {
bears: number
fetchBears: () => Promise<void>
}
export const useBearStore = create<BearState>()((set) => ({
bears: 0,
fetchBears: async () => {
const res = await fetch('/api/bears')
const data: BearData = await res.json()
set({ bears: data.count })
},
}))The async action fetches remote data, converts the response to the declared type, and stores the returned count.
A component needs current server data such as a count or list.
A request result must be validated by the TypeScript shape used by the store.
An action should encapsulate loading data and committing it to Zustand state.
Declare the action as a function returning Promise<void>, perform the asynchronous request inside it, await the parsed response, and call set with the new state. The documented example types the response as BearData before updating bears.
Follow-up: How would you preserve response typing? Define an interface for the response shape and annotate the parsed JSON value, as in BearData.
The action is placed alongside the state in the object returned by create. Its body can use set after asynchronous work completes, so the store changes when the remote result is available.
Follow-up: Can async work be placed outside the store? The cited page does not document that pattern for async actions, so it should not be inferred from this card.
The action returns Promise<void> because it performs asynchronous work but does not expose a result; it updates the bears field through set. The fetched count becomes the stored value.
Follow-up: What if callers need the fetched value? The page does not specify a return-value pattern, so define and document that API separately rather than assuming one.
createsetBearDatafetchBears