Skip to content
Advertisement

Why won’t setMatrix([…matrix, [[x][y]]]) work?

I want to add the coordinates x and y (from the loop) to the state (matrix) like you can see in my example but it won’t work. Can someone help me?

const [matrix, setMatrix] = useState([[], []] as any)

for (let j = 0; j < imgHeight * scale; j += props.gridsize.height) {
  for (let i = 0; i < imgWidth * scale; i += props.gridsize.width) {
    console.log('x: ' + x + ' ===== ' + 'y: ' + y)
    drawImgRectangles(ctx, [{ x: x, y: y, width: props.gridsize.width, height: props.gridsize.height }])
    x += props.gridsize.height

  }
  x = 0
  y += props.gridsize.height
}
setMatrix([...matrix, [[x][y]]])
console.log(matrix[[0][0]]) **

Advertisement

Answer

The problem is in expression [x][y] which evaluates to undefined.

  • [x] defines an array containing one element x
  • [x][y] tries to index the [x] array, taking y-th element. If y is anything other than 0, the result is undefined
console.log([3][0]);  // 3
console.log([3][1]);  // undefined

You probably meant one of:

const x = 1;
const y = 2;

var matrix1: number[][] = [];
matrix1 = [...matrix1, [x, y]];

var matrix2: number[][][] = [];
matrix2 = [...matrix2, [[x], [y]]];
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement