reactjsnext.jszustand

Automated Re-fetching API in zustand


I want to call to fetchConsultingList() after call to addConsulting() successfully. I used redux toolkit query to do this thing in previous project but now I want to do it using zustand.

I tried to call fetchConsultingList() in addConsulting() but its has an error:

fetchConsultingList is not defined.

import { create } from "zustand";
import API from "../services/API";

const useConsultingStore = create((set) => ({
  consultingList: null,
  fetchConsultingList: async () => {
    const response = await API.TestES.getListConsulting();
    if (response.data.code === "0") {
        set({ consultingList: response.data.data });
    } else {
        set({ consultingList: null });
    }
  },
  addConsulting: async () => {
    const response = await API.TestES.addConsultingPackage();
    fetchConsultingList(); // fetchConsultingList is not defined
  }
}));
export default useConsultingStore;

Solution

  • Similar to set, create also provide get as second parameter and you need to use that to access to get the current state.

    Here's the complete code:

    import { create } from "zustand";
    import API from "../services/API";
    
    const useConsultingStore = create((set, get) => ({
      consultingList: null,
      fetchConsultingList: async () => {
        const response = await API.TestES.getListConsulting();
        if (response.data.code === "0") {
            set({ consultingList: response.data.data });
        } else {
            set({ consultingList: null });
        }
      },
      addConsulting: async () => {
        const response = await API.TestES.addConsultingPackage();
        await get().fetchConsultingList();
      }
    }));
    
    export default useConsultingStore;
    

    Read from state in actions