React Js / APIs / Api with zustand store - Basics
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 Loading users...
; if (error) returnError: {error}
; return (); }; export default UserList;Users from API (Zustand)
-
{users.map(user => (
- {user.name} - {user.email} ))}
4. Add It in App.jsx
import UserList from './components/UserList'; function App() { return ( ); } export default App;Zustand + API Example
MANVIA BLOG