Search code examples
reactjszustand

How to set object key in state using zustand


I am using zustand for state management. My store is setup as follow :

import create from 'zustand';

export const useStore = create((set) => ({
    filters: {searchQuery: 'hello', evaluationMonth : null},
    setFilters: (e) => set((state) => ({filters : {evaluationMonth : 'New Month'}})),
}))

When i call setFilters I only expect evaluationMonth to change, but it's also removing the existing values (searchQuery in this case). How do i persist the old statet while changing the desired values.


Solution

  • You can do this by spreading the state parameter in the set function. Make sure that the value(s) you want to override is the last element in the object to avoid it being overridden by the old state spread.

    export const useStore = create((set) => ({
        filters: {searchQuery: 'hello', evaluationMonth : null},
        setFilters: (e) => set((state) => ({filters : {...state.filters, evaluationMonth : 'New Month'}})),
    }))