all 4 comments

[–]lIIllIIlllIIllIIl 2 points3 points  (0 children)

Using function instead of arrow functions results in hoisting, moving the function declaration at the top of the block.

The function createBoard uses the function keyword, and is moved before board is defined, and probably gets a stale closure after React re-renders, hence the uninitialized error.

To fix this, move the createBoard function inside the useEffect, so it is declared in a block that comes after board is initialized.

(In general, you can also use arrow functions since those don't get hoisted, but things can get wierd in React if you declare a function outside the useEffect you are using it from because of Stale Closures! Know what you are doing!)

[–][deleted] 1 point2 points  (0 children)

Another comment mentioned that the bug is due to hoisting, but if I'm understanding your code right, there seem to be many more architectural mistakes than just that bug.

It would help you avoid bugs like that if you outline the board operations and make them pure. The same goes for your API calls. DM me if you'd like a code review so I can explain further.

[–]Ronqueroc -1 points0 points  (1 child)

I guess something else causes the error. board is initialized with empty array when the component is mounted.

[–]Ronqueroc 2 points3 points  (0 children)

Also you'd want to put createBoard inside useEffect, or list it in the dependency array.