Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

189
Views
TypeError: squares.slice is not a function on trying to make a copy of the array

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 ['', '', '', '', '', '', '', '', '']

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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"

Suggestion

Instead of .slice() I would change the newSquares like this:

const newSquares = squares.map((sq, index) => index === i ? (isX ? "X" : "O") : sq)
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!