How to properly call and execute a function from a Zustand store?

666 Views Asked by At

I've written out a function below in my Store.tsx component that calculates square footage of a room based on width, length and height. Upon updating my Store file with this component, I get the following error:

"Uncaught TypeError: Cannot read properties of undefined (reading 'toLocaleString')"

Tried removing the toLocaleString from the Results component below, but then the browser crashes. I'm thinking I'm improperly calling setSquareFeet in my Results component below, and that may be leading to the crash.

How do I correctly call and execute my store's setSquareFeet function in my Result component?

Store:

const useCalcSquareFeetStore = create<useCalcSquareFeet>((set: any) => ({
  width: 0,
  length: 0,
  height: 0,
  squareFeet: 0,
  setWidth: (value) => set({ width: value }),
  setLength: (value) => set({ length: value }),
  setHeight: (value) => set({ height: value }),
  setSquareFeet: () => { // this is the function I'd like to make work
    set((state: any) => ({
      squareFeet: state.width * state.length * state.height,
    }));
  },
}));

export default useCalcSquareFeetStore;

SquareFeet component:

<Result
  heading="Number of square feet"
  number={setSquareFeet()} // Use the function from the store
/>

Result component:

export const Result: React.FC<Props> = ({ heading, number }) => {
  return (
    <div className="result">
      <h4 className="heading">{heading}</h4>
      <h4 className="number">{number.toLocaleString()}</h4>
    </div>
  );
};
1

There are 1 best solutions below

0
Богдан Лавриненко On

i think u need to do something like this

const YourComponent = () => {
  const { setSquareFeet } = useCalcSquareFeetStore();
  // or u can use this
  // const setSquareFeet = useCalcSquareFeetStore(state=>state.setSquareFeet);


  return (
    <>
      <Result
        heading="Number of square feet"
        number={setSquareFeet()} // call your function here
      />
    </>
  )
};

export default YourComponent;