Home > other >  Is there a way to create a reusable state update function in Zustand?
Is there a way to create a reusable state update function in Zustand?

Time:07-28

I am trying to learn Zustand and came across a tricky question.

Can I create a reusable function to set my state?

The example is very contrived, but I would like to display animal populations across many React components. The idea is to use the same increasePopulation function for any animal. I believe vanilla JavaScript uses the bracket notation for this, but I am struggling to make it work with Zustand

This is my store:

import create from 'zustand'

const useAnimalStore = create((set) => ({
    bears: 0,
    cats: 5,
    dogs: 20,
    increasePopulation: (animal) => set((state) => ({ [animal]: state.[animal]   1 })),
}))

Many thanks and apologies if this is too newbie-like question

CodePudding user response:

You were just using dot and bracket notation at the same time.

const useAnimalStore = create((set) => ({
  bears: 0,
  cats: 5,
  dogs: 20,
  increasePopulation: (animal) =>
   // state[animal] not state.[animal]
    set((state) => ({ [animal]: state[animal]   1 }))
}));

CodeSandBox : https://codesandbox.io/s/epic-moore-mfr1f2?file=/src/store.js:31-200

CodePudding user response:

instead of direct using variables wrap those into an object and update object with zustand set funtion and spread operator.

import create from 'zustand'

const useAnimalStore = create((set) => ({
  animals: {
      bears: 0,
    cats: 5,
    dogs: 20,
    },
    increasePopulation: (animal) => set((state) => ({ animals: { ...state.animals, [animal]: state.animals[animal]   1 } })),
}))

  • Related