Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

190
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda