How to handle asynchronous operations in Zustand:
-
Basic asynchronous operations
- Define async actions in the store
- Use async/await syntax
- Example:
javascript
import { create } from 'zustand'; const useUserStore = create((set) => ({ user: null, isLoading: false, error: null, fetchUser: async (userId) => { set({ isLoading: true, error: null }); try { const response = await fetch(`https://api.example.com/users/${userId}`); const user = await response.json(); set({ user, isLoading: false }); } catch (error) { set({ error: error.message, isLoading: false }); } }, }));
-
Using Promises
- Return Promise so components can wait for operation completion
- Example:
javascript
fetchUser: async (userId) => { set({ isLoading: true, error: null }); try { const response = await fetch(`https://api.example.com/users/${userId}`); const user = await response.json(); set({ user, isLoading: false }); return user; // Return result } catch (error) { set({ error: error.message, isLoading: false }); throw error; // Throw error } },
-
Handling multiple async operations
- Execute multiple async operations in parallel
- Example:
javascript
fetchMultipleData: async () => { set({ isLoading: true }); try { const [user, posts] = await Promise.all([ fetch('https://api.example.com/user').then(res => res.json()), fetch('https://api.example.com/posts').then(res => res.json()) ]); set({ user, posts, isLoading: false }); } catch (error) { set({ error: error.message, isLoading: false }); } },
-
Middleware handling
- Use custom middleware to handle async operations
- Example:
javascript
const asyncMiddleware = (store) => (next) => (action) => { if (typeof action === 'function') { return action(store.getState, store.setState); } return next(action); }; const useStore = create( asyncMiddleware((set, get) => ({ // State and actions })) );
-
Best practices
- Always handle loading and error states
- Provide cancellation mechanisms for async operations
- Properly use try/catch for error handling
- Consider using SWR or React Query for complex async data
-
Common async scenarios
- API calls
- Data loading and caching
- File uploads and downloads
- Authentication and authorization operations