When using Zustand to manage state in your React application, you can create a simple global state store to store the results of API queries. Here are the steps to create and use a Zustand store:
1. Install Zustand
First, you need to install Zustand in your project (if you haven't already).
shnpm install zustand
Or use yarn:
shyarn add zustand
2. Create a Zustand Store
Create a new file in your project, such as useStore.js, and define a Zustand store using the create method.
javascriptimport create from 'zustand'; const useStore = create((set) => ({ apiData: null, // state for storing the results of API queries setApiData: (data) => set({ apiData: data }), // action to update the apiData state }); export default useStore;
3. Fetch Data and Update the Store in a Component
In the component, you can use the defined useStore hook to store the results of API queries.
javascriptimport React, { useEffect } from 'react'; import axios from 'axios'; import useStore from './useStore'; // import the store we created const SomeComponent = () => { const { apiData, setApiData } = useStore(); useEffect(() => { const fetchData = async () => { try { const response = await axios.get('https://your-api.com/data'); setApiData(response.data); // update the apiData in the store } catch (error) { console.error('Fetching data failed: ', error); // Handle errors here, e.g., set an error state } }; fetchData(); }, [setApiData]); // If setApiData is a stable function, you can omit the dependency array // Render data or loading state if (!apiData) return <div>Loading...</div>; return ( <div> {/* Render the results of the API query */} {apiData.map((item) => ( <div key={item.id}>{item.title}</div> ))} </div> ); }; export default SomeComponent;
4. Use the API Data
You can access the apiData state by calling the useStore hook in any component of your application and render based on it.
Example Explanation
In the above example:
useStoredefines two properties:apiDatafor storing API data, andsetApiDatafor updating it.- The
SomeComponentcomponent fetches the API data on mount and usessetApiDatato store the results in the global state. - Within the component, you can directly access
apiDatato render the API data.
This way, you can store and access API query results in your React application using the Zustand global state management library. The benefit of this approach is that the state management logic is concise, easy to test and maintain, and allows sharing and updating state across components.