Home > Enterprise >  Uncaught TypeError: Cannot read properties of undefined (reading '0'), Summing useState ar
Uncaught TypeError: Cannot read properties of undefined (reading '0'), Summing useState ar

Time:12-11

    const [lnames, setlNames] = React.useState();
    const [lnums, setlNums] = React.useState();
    
    React.useEffect(() => {
      axios.get("http://localhost:7001/lunch").then(response => {
        let arr1 = [];
        let arr2 = [];
    
        response.data.forEach(c => {
          arr1.push(c.table_id);
          arr2.push(c.table_num_count);
        });
    
        setlNames(arr1);
        setlNums(arr2);
      });
    }, []);
    
    const [dnums, setdNums] = React.useState();
    
    React.useEffect(() => {
      axios.get("http://localhost:7001/dinner").then(response => {
        let arr1 = [];
        response.data.forEach(c => {
          arr1.push(c.table_num_count);
        });
        setdNums(arr1);
      });
    }, []);
    
    const [bnums, setbNums] = React.useState();
    
    React.useEffect(() => {
      axios.get("http://localhost:7001/breakfast").then(response => {
        let arr1 = [];
        response.data.forEach(c => {
          arr1.push(c.table_num_count);
        });
        setbNums(arr1);
      });
    }, []);
    
    const customer_count_breakfast = bnums;
    const customer_count_lunch = lnums;
    const customer_count_dinner = dnums;
    
    let sumArray = []
    
if (lnums & lnums.length > 0) {
  //sumArray = lnums.map((l, i) => l   bnums[i]   dnums[i]);
  for (let i = 0; i < lnums.length; i  ) {
    sumArray[i] = bnums[i]   lnums[i]   dnums[i];
  }
}

// IF COMMENT ABOVE AND UNCOMMENT HERE THE ERROR IS GONE BUT sumArray is not computed
// if (lnums && lnums[0]) {
//   //sumArray = lnums.map((l, i) => l   bnums[i]   dnums[i]);
//   for (let i = 0; i < lnums.length; i  ) {
//     sumArray[i] = bnums[i]   lnums[i]   dnums[i];
//   }
// }

Hello I have the above code giving me the following error at the if loop condition : Uncaught TypeError: Cannot read properties of undefined (reading '0'). I think I know why the error is being displayed. It is indicating that I am trying to access a property or index of a variable that is undefined, this is most likely due to the useEffect, where when I call for the if condition the value is not set yet, so it is undefined and thus does not have a length. When I try to comment the first if condition and uncomment the second, I get no more errors but the summation does not work, it returns an empty array.

How would I be able to sum the values of .useState() variables in this case?

CodePudding user response:

I solved the issue by adding a try-catch statement, not sure if it is feasible at all

try {
  for (let i = 0; i < lnums.length; i  ) {
    sumArray[i] = bnums[i]   lnums[i]   dnums[i];
  }
  console.log("Statement was successful");
} catch (error) {
  
} 

CodePudding user response:

You need to look into react lifecycle and useMemo.

read about lifecycle: https://www.w3schools.com/react/react_lifecycle.asp

read about useMemo: https://www.w3schools.com/react/react_usememo.asp

Here is a quick example where useEffect puts numbers into an array, useMemo has dependency on those arrays and adds all the numbers together.

import { useEffect, useState, useMemo } from "react";

export default function App() {
  const [arr1, setArr1] = useState([]);
  const [arr2, setArr2] = useState([]);

  // called everytime arr1 or arr2 changes. Which causes react to rerender.
  // first run sum = 0
  const sum = useMemo(() => {
    let res = 0;

    if (arr1.length && arr2.length) {
      for (let i = 0; i < arr1.length; i  ) {
        res  = arr1[i]   arr2[i];
      }
    }

    return res;
  }, [arr1, arr2]);

  // called once, updated setArr1 causing sum to be called
  useEffect(() => {
    setArr1([1,2,3]);
  }, []);

  // called once, updated setArr2 causing sum to be called
  useEffect(() => {
   setArr2([4,5,6]);
  }, []);

 return (
  <div>
   <p> sum: {sum} </p>
  </div>
 );

}

Essentially In your code you are calling the arrays before useEffect has finished setting their values.

  • Related