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

124
Vistas
Problem with setState looping inside an array Next.js

Can't find a way to solve my problem its looping correctly the first time but after looping twice in the array I got an error "TypeError: props.imgData[index] is undefined".

Here is my code :

import React, { useEffect } from "react";

import Image from 'next/image';

export default function SimpleSlider(props) {
   
  let matchingIdArray = props.imgData.findIndex(element => {
    return element.id === props.id 
  })
  
let [index,setIndex] = React.useState(matchingIdArray )
console.log(index)

  let next = () => {    
   setIndex(prev => 
      {
      if(prev <props.imgData.length -1 )       {
       return   prev +1      
        }
        else {
       setIndex(0)
        }
    } )     
  } 
  return (
    <section className="w-full h-screen mx-auto">
  
  <div onClick={next}  className=" w-3/4 mx-auto h-screen  ">      
  <Image src={props.imgData[index].urls.raw} width={props.imgData[index].width} height={props.imgData[index].height} quality={100}  /> 
  </div>
         
    </section>
  )
}
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Why setIndex(0) instead of return 0 ? You're not returning anything in this case so you're in fact doing setState(undefined)

about 4 years ago · Juan Pablo Isaza Denunciar

0

according to your code its getting setIndex itself to set function when

prev > props.imgData.length -1

try to return 0 instead setIndex(0)

let next = () => {    
   setIndex(prev => 
      {
      if(prev <props.imgData.length -1 ){
       return   prev +1;
        }
        else {
       return 0;
        }
    } )     
  } 
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