API with zustand

  • 1. Step

    1. Install Zustand

    
                  npm install zustand
    

    2. Create Zustand Store

    src/store/userStore.js

    
    
    import { create } from 'zustand';
    
    const useUserStore = create((set) => ({
      users: [],
      loading: false,
      error: null,
    
      fetchUsers: async () => {
        set({ loading: true, error: null });
        try {
          const res = await fetch('https://jsonplaceholder.typicode.com/users');
          if (!res.ok) throw new Error('Failed to fetch');
          const data = await res.json();
          set({ users: data, loading: false });
        } catch (err) {
          set({ error: err.message, loading: false });
        }
      }
    }));
    
    export default useUserStore;
    
    
    

    3. Use Store in a Component

    src/components/UserList.jsx

    
    
    import { useEffect } from 'react';
    import useUserStore from '../store/userStore';
    
    const UserList = () => {
      const { users, fetchUsers, loading, error } = useUserStore();
    
      useEffect(() => {
        fetchUsers();
      }, []);
    
      if (loading) return <p>Loading users...</p>;
      if (error) return <p>Error: {error}</p>;
    
      return (
        <div>
          <h2>Users from API (Zustand)</h2>
          <ul>
            {users.map(user => (
              <li key={user.id}>
                <strong>{user.name}</strong> - {user.email}
              </li>
            ))}
          </ul>
        </div>
      );
    };
    
    export default UserList;
    
    

    4. Add It in App.jsx

    
      import UserList from './components/UserList';
    
    function App() {
      return (
        <div>
          <h1>Zustand + API Example</h1>
          <UserList />
        </div>
      );
    }
    
    export default App;