Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

zustand stores manage loading state

// This is the store for Page1
const usePageModel1 = create(set => {
  result: null,
  loading: false,
  error: null,
  fetchData1: async (id)=> {
    try {
      set({ loading: true })
      const result = await (await fetch(`/api1/${id}`)).json()  // load data from api1
      set({ loading: false, result })
    } catch(error) {
      set({ loading: false, error })
    }
  },
});

const Page1 = () => {
   const model = usePageModel1();
   // ...
}

// This is the store for Page2
const usePageModel2 = create(set => {
  result: null,
  loading: false,
  error: null,
  fetchData2: async (id)=> {
    try {
      set({ loading: true })
      const result = await (await fetch(`/api2/${id}`)).json()  // load data from api2
      set({ loading: false, result })
    } catch(error) {
      set({ loading: false, error })
    }
  },
});

const Page2 = () => {
   const model = usePageModel2();
   // ...
}
Source by github.com #
 
PREVIOUS NEXT
Tagged: #zustand #stores #manage #loading #state
ADD COMMENT
Topic
Name
4+4 =