How to set state in react whith the content at a certain index from an array

I have an array of reviews and I want to update the state whith the review at a certain index, on click. Can somebody explain wthy the code below isnt working? and mabie provide a solution? the reviews are passed down through props. the console log shows me 2, 2, 3 and the again 2,2 3. I Have 5 reviews. And Wierd enough, If i comment the setReview line , the console shows as expected.

const InfoSection = ({ reviews}) => {
 let index = 1;
 let [review, setReview] = useState('some initial state');

 const paintNextReview = () => {
  //   index >= reviews.length ? (index = 0) : (index = index);
  setReview(reviews[index]);
   index++;
  console.log(index);
  
 };
 return(
 <div>
 
          <div >{review}</div>
          <button onClick={paintNextReview}> click</button>
 </div>
 )
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>



Read more here: https://stackoverflow.com/questions/67394944/how-to-set-state-in-react-whith-the-content-at-a-certain-index-from-an-array

Content Attribution

This content was originally published by George Murgoci at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: