Zustand doesn't retrieve updated values, displays initial values instead

21 views Asked by At

I'm encountering an issue with Zustand where updated values are not retrieved when I try to access them. Specifically, I'm setting the totalPrice value as an initial value in Zustand, and after updating it, when I try to retrieve the value again, the initial value is displayed first, followed by the updated value. This behavior is consistent for all Zustand values I've configured. I'm puzzled as to why this is happening. Any insights or suggestions on how to resolve this issue would be greatly appreciated.

This is my zustand code.

import {create} from 'zustand';

import {persist} from 'zustand/middleware';

interface IFirstSurveyStore {
  zustandMonitorUsage: -1 | 1 | 2 | 4 | 8 | 16;
  setZustandMonitorUsage: (newUsage: -1 | 1 | 2 | 4 | 8 | 16) => void;
  zustandTotalPrice: number;
  setZustandTotalPrice: (newPrice: number) => void;
  resetFirstSurvey: () => void;
}

const useFirstSurveyStore = create<IFirstSurveyStore>()(
  persist(
    set => ({
      zustandMonitorUsage: -1,
      setZustandMonitorUsage: (newUsage: -1 | 1 | 2 | 4 | 8 | 16) =>
        set({zustandMonitorUsage: newUsage}),
      zustandTotalPrice: 10,
      setZustandTotalPrice: (newPrice: number) =>
        set({zustandTotalPrice: newPrice}),
      resetFirstSurvey: () => {
        set({
          zustandMonitorUsage: -1,
          zustandTotalPrice: 0,
        });
      },
    }),
    {name: 'FirstSurvey'},
  ),
);

export default useFirstSurveyStore;
export type {IFirstSurveyStore};

After I update I checked updated value goes well by developer tools. But if i change page(that console the zustandTotalPrice), zustandTotalPrice is still the updated value at the developer tools, but when I console it, the initial value(10) comes and after that updated value comes.

const DoubleHandleRangeSlider = () => {
  const {setZustandTotalPrice, zustandTotalPrice} = useFirstSurveyStore();
  const [maxValue, setMaxValue] = useState(zustandTotalPrice);

  const handleMaxChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const newMax: number = parseInt(event.target.value, 10);
    setMaxValue(newMax);
  };

  useEffect(() => {
    const saveMaxValue = () => {
      setZustandTotalPrice(maxValue);
    };
    const timerId = setTimeout(saveMaxValue, 500);
    return () => clearTimeout(timerId);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [maxValue]);

  console.log(zustandTotalPrice);
return(<></>);
};

In my opinion, zustandTotalPrice changed the value and persisted it(at the developer tools) so If I call it, then the updated value should come. I can't understand why the initial value comes.

0

There are 0 answers