Home > Blockchain >  Problem with setState looping inside an array Next.js
Problem with setState looping inside an array Next.js

Time:06-03

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>
  )
}

CodePudding user response:

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

CodePudding user response:

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;
        }
    } )     
  } 
  • Related