Rahul Kumar
Rahul Kumar

Reputation: 109

React TypeError: Cannot read property '0' of undefined

I am writing a function to calculate the individual column total of 12 rows and create a new array of the total values of the same size but i keep getting the error

TypeError: Cannot read property '0' of undefined how do i resove it

new_matrix of dimension [6][12] is pre calculated and then passed into the colTotaler function as also the matrix input is obtained through a matrix input form

colToataler(new_matrix);

let columns = [0,0,0,0,0,0,0,0,0,0,0,0];

const[col,setCol] = useState(columns);

const colTotaler = (new_matrix) => {
   let i = 0,
     j = 0;

   for (i = 0; i < new_matrix[0].length; i++) {
     for (j = 0; j < new_matrix.length; j++) {
       columns[i] += new_matrix[i][j];
     }
   }

   setCol(columns);
 };

Upvotes: 0

Views: 94

Answers (2)

Mike Kokadii
Mike Kokadii

Reputation: 513

The way you choose to calculate colTotaler isn't good enought. I would suggest you to do this in functional way, using map, reduce and reactivity of React:

const [matrix, setMatrix] = useState(defaultMatrix)

const colTotaler = matrix.map((column) => {
  return column.reduce((colTotal, element) => colTotal+ element, 0)
})

Now, every time when setMatrix will be called, component will rerendered and colTotaler will be recalculated.

Upvotes: 2

Eugene
Eugene

Reputation: 1533

If you pass new_matrix from state, the initial value of the state could be undefined. To fix that you can add if statement to check it state is initialized:

let comumns = [0,0,0,0,0,0,0,0,0,0,0,0];

const[col,setCol] = useState(columns);

const colTotaler = (new_matrix) => {
   if (new_matrix) {
     let i = 0,
       j = 0;

     for (i = 0; i < new_matrix[0].length; i++) {
       for (j = 0; j < new_matrix.length; j++) {
         columns[i] += new_matrix[i][j];
       }
     }

     setCol(columns);
   }
 };

Upvotes: 0

Related Questions