In my component in react, I am trying to make a copy of an array. But the function keeps failing on the point when I actually call the slice method. Here's my full code for better context
const Board = ()=>{
const [squares, setSquares] = useState(Array(9).fill(""))
const [isX , setIsX] = useState(true)
const [stepNumber, setStepNumber] = useState(0)
const [winner, setWinner] = useState(null)
console.log(`squares is ${Array.isArray(squares)}`, squares.slice())
const onClick = (i)=>{
console.log("On CLick")
if(winner || stepNumber>9) return;
console.log(squares)
const newSquares = squares.slice()
(isX) ? newSquares[i] = "X" : newSquares[i]= "O"
setIsX(!isX)
setWinner(newSquares)
if(winner){
console.log(winner)
}
setSquares(newSquares)
setStepNumber(stepNumber+1)
}
return(
<div className = "board">
{squares.map((square , i) => {
return(
<Square key={i} data-key={i} value={square}
onClick = {()=>onClick(i)} />)
})}
</div>
)
}
The line where I declare newSquares keeps failing with the error:TypeError: squares.slice(...) is not a function . Can somebody please tell what am I doing wrong?
EDIT: Here's the output of squares ['', '', '', '', '', '', '', '', '']
In a one-line conditional statement, you are doing the assignment wrong. The problem is in this line:
(isX) ? newSquares[i] = "X" : newSquares[i]= "O"
Change that to:
newSquares[i] = isX ? "X" : "O"
Instead of .slice() I would change the newSquares like this:
const newSquares = squares.map((sq, index) => index === i ? (isX ? "X" : "O") : sq)