Next.js Discord

Discord Forum

Why subscribe doesn't work with zustand?

Unanswered
Siberian Rubythroat posted this in #help-forum
Open in Discord
Siberian RubythroatOP
why when state gets update subscribe doesn't work?
const useCartStore = create(subscribeWithSelector(cartStore))

useCartStore.subscribe(
  state => state.food,
  food => {
    console.log(202)
    if (typeof window === "undefined") return
    const storage = getStorage()
    storage.saveFood(food)
  },
)

export default useCartStore

I expect - when I change state.food - I got console log 202

1 Reply

Siberian RubythroatOP
subscribe has 2 overloads and second overload for some reason doesn't work for me

// don't use this approach cause it doesn't work
// useCartStore.subscribe(
//   state => state.food,
//   food => {
//     console.log(202)
//     if (typeof window === "undefined") return
//     const storage = getStorage()
//     storage.saveFood(food)
//   },
// )

useCartStore.subscribe((state, prevState) => {
  console.log(202)
  if (typeof window === "undefined") return
  const storage = getStorage()
  storage.saveFood(state.food)
})