Sub topic 7
Async actions and loading state
This chapter assumes you can write a basic Zustand store, read it with selectors, and update it with set. It also assumes you know async/await and fetch. Here you will put a network request inside a store action and track its progress.
Actions can be async
Zustand has no special API for async work. An action is a function, so it can be async. You call set as many times as you need while the function runs.
The usual pattern has three states: loading, success, and failure. You set loading before the request, then set the result and clear loading afterward.
import { create } from 'zustand'
interface User {
id: number
name: string
}
interface UsersState {
users: User[]
loading: boolean
error: string | null
fetchUsers: () => Promise<void>
}
export const useUsersStore = create<UsersState>()((set) => ({
users: [],
loading: false,
error: null,
fetchUsers: async () => {
set({ loading: true, error: null })
try {
const response = await fetch('/api/users')
if (!response.ok) throw new Error(`Request failed: ${response.status}`)
const users: User[] = await response.json()
set({ users, loading: false })
} catch (e) {
set({ error: e instanceof Error ? e.message : 'Unknown error', loading: false })
}
},
}))Three details matter here:
setmerges, so each call changes only the fields you pass.userskeeps its old value while a reload is in progress.fetchdoes not reject on HTTP errors such as 404 or 500. Theresponse.okcheck turns them into thrown errors, so they reach thecatchblock.- Both the success and failure paths set
loading: false. If one path forgot, the spinner would never go away.
Using the store in a component
Select each field separately. Each selector returns a primitive or a stable reference, so the component re-renders only when that value changes.
import { useEffect } from 'react'
import { useUsersStore } from './usersStore'
function UserList() {
const users = useUsersStore((state) => state.users)
const loading = useUsersStore((state) => state.loading)
const error = useUsersStore((state) => state.error)
const fetchUsers = useUsersStore((state) => state.fetchUsers)
useEffect(() => {
fetchUsers()
}, [fetchUsers])
if (loading) return <p>Loading...</p>
if (error) return <p>Error: {error}</p>
return (
<ul>
{users.map((u) => (
<li key={u.id}>{u.name}</li>
))}
</ul>
)
}The action reference is stable, because it is created once with the store. Listing it in the effect dependencies is safe and does not cause a loop.
Common errors
- Overlapping requests. If
fetchUsersruns twice quickly, the slower response overwrites the faster one, and the first to finish setsloadingto false too early. Guard withif (get().loading) return. For this you needgetas the second argument of the state creator, as in(set, get) => .... - Unhandled rejections. Without
try/catch, a failed request throws inside the action and theerrorfield never updates. - Several booleans for one process. Fields like
isLoading,isSuccess, andisErrorcan contradict each other. A singlestatusfield with values such as'idle' | 'loading' | 'success' | 'error'rules out impossible combinations.
Exercise
In the fetchUsers action, why does the code call set({ loading: true, error: null }) before the request starts, and what bug appears if the catch block omits loading: false?
Show answer
Setting loading: true lets the UI show a spinner during the request, and clearing error removes the message from any earlier failed attempt. If catch omits loading: false, a failed request leaves loading true, so the component keeps showing "Loading..." and never reaches the error message.