#Zustand state reset issue

33 messages · Page 1 of 1 (latest)

hushed mulch
#

Hi,

So I've got store with some variables, and a reset function. In the reset function when I try to set state to const with initialState for some reason it doesn't work, but when I manually write the same content it does. Why?

Initial state:

const initState = {
  currentTick: 0,
  // speed
  speed: 3,
  // interval ref
  interval: 0,
  menu: true,
  // starting snake
  snake: [[10, 2]],
};

Reset function that doesn't work:

const useGameStateStore = create<GameState>()((set) => ({
  ...initState,
  reset: () =>
    set((state) => ({
      ...initState,
    })),
}));

Reset function that does work:

const useGameStateStore = create<GameState>()((set) => ({
  ...initState,
  reset: () =>
    set((state) => ({
      currentTick: 0,
      // speed
      speed: 3,
      // interval ref
      interval: 0,
      menu: true,
      // starting snake
      snake: [[10, 2]],
    })),
}));
sudden minnow
#

Can you provide a reproduction of it not working on codeblitz or codesandbox? Your first snippet looks like it should work just fine

#

@hushed mulch

hushed mulch
#

@sudden minnow Ill do that

sudden minnow
#

Ah ok

#

When you say the state isn't being reset, you're saying that - in particular - the snakes position isn't being reset

#

Is that right? @hushed mulch

hushed mulch
#

yes

sudden minnow
#

The issue is in your App.tsx file, in the move function

#

you're directly mutating the snake array of positions

#

that's changing the snake property on your initState object

hushed mulch
#

aaaa

sudden minnow
#

You are resetting the state to initState correctly, but because you directly mutated initState, you keep the same position of the snake

#

Also, direct mutations like this don't tell zustand to update React with the new state

hushed mulch
#

but wait

sudden minnow
#

your snake is only moving because you likely have some other tick code or something updating your state

hushed mulch
#

the const initState is not being mutated

sudden minnow
#

mmm let me double check

hushed mulch
#

in the store i spread the initstate

#

so it should not be doing anything to initstate

#

this is the only place whe its being called

sudden minnow
#

You are spreading the object, but your snake property is an array

#

spread doesn't copy nested objects/arrays

#

The same snake array is being shared

hushed mulch
#

so whats the quick fix to this?

sudden minnow
#

no quick fix. You need to extract that whole move function from your App component into your zustand store

#

or at least add in a method to the store to add a new position

hushed mulch
#

ok, Ill try doing that. Thank You @sudden minnow ! 🙂

sudden minnow
#

notice that i commented out the snake.pop() in move() too, as that also mutates the array

hushed mulch
#

Yeah I see. Thank You for the help 🙂