Zustand and Event Listerners

31 Views Asked by At

Please help me here, I am importing the windowSize variable, I always get undefined in the first time it's called, but when I resize it works perfectly;

This is the way I am importing it since destructring is not working.

const windowSize = useWindowSizeStore((state: any) => state.windowSize);

the first log inside my componentis ("undefined")

import { create } from "zustand";

const initialSize = window.innerWidth;

const useWindowSizeStore = create((set) => {
  const handleResize = () => {
    set((state: any) => ({ ...state, windowSize: window.innerWidth }));
  };

  set({
    windowWidth: initialSize,
  });
  
  window.addEventListener("resize", handleResize);

  return () => window.removeEventListener("resize", handleResize);
});

export default useWindowSizeStore;
0

There are 0 best solutions below