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

122
Views
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 answers
Answer question

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 Report

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 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!