乐闻世界logo
搜索文章和话题

How to handle asynchronous operations in Zustand?

3月7日 11:44

How to handle asynchronous operations in Zustand:

  1. 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 }); } }, }));
  2. 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 } },
  3. 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 }); } },
  4. 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 })) );
  5. 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
  6. Common async scenarios

    • API calls
    • Data loading and caching
    • File uploads and downloads
    • Authentication and authorization operations
标签:Zustand