const cats = [
1, 2, 3
];
let arr = [];
const [images, setImages] = useState([]);
const generateCat = () => {
fetch(
"https://api.thecatapi.com/v1/images/search?size=small&limit=1&mime_types=jpg,png&width=200&height=200"
)
.then(response=>{return response.json()})
.then(data=>{
let finalResult = data[0]['url']
arr.push(finalResult)
console.log(arr)
return finalResult
})
};
for(let i=0;i<cats.length;i++){
generateCat()
setImages(arr)
console.log('Images: '+images)
}
My problem is that I’m encountering an issue with setState() causing an infinite loop in my React component. Specifically, I’m making an API call to retrieve an image of a cat and pushing the image URL to an array called arr. Then, I’m attempting to update the state of the component by calling setImages(arr) and logging the images variable to the console.
However, calling setImages() triggers a re-render of the component, which causes the for loop to execute again, leading to another API call, another push to arr, and another call to setImages(), resulting in an infinite loop.
I am expecting the state variable images
to have 3 img urls since the for loop is being iterated thrice.
2
Answers
I am assuming this code is inside of a react component so here is modified example that should prevent the pre-rendering:
You need to wrap your fetch operations in a
useEffect
: