Why subscribe doesn't work with zustand?

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
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
Nikita
NikitaOP12mo ago
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)
})
// 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)
})
Want results from more Discord servers?
Add your server