I am trying to call this endpoint to generate random memes when a a user clicks on a button. I am using the fetch api inside the useEffect hook,and the button works fine, but when I click it, there is splash of a new image for a split second and then the image disappears as the app gets re-rendered. I do not know why this is happening.
Here is my code:
import {useState, useEffect, useCallback} from 'react';
const Ui = () => {
// updating the state
const [url, setUrl ] = useState({})
const [meme, setMeme ] = useState([])
useEffect(()=>{
fetch('https://api.imgflip.com/get_memes')
.then(res => res.json())
.then(data=> setMeme(data.data.memes))
}, [])
// function that brings a random image
const getAMeme = ()=>{
const randomNum = Math.floor(Math.random() * meme.length)
const url = meme[randomNum].url
console.log(url)
setUrl(prevUrl =>({
...prevUrl,
randomImage: url
}))
}
return (
<div className = "ui">
{/* form */}
<form>
<input placeholder="Enter first sentence"></input>
<input placeholder="Enter second sentence"></input>
<button onClick={getAMeme}>Generate Meme</button>
</form>
{/* meme image */}
<div className="image">
<img src={url.randomImage} alt="cool" />
</div>
</div>
);
}
export default Ui;
I am calling the endpoint inside the useEffect but it seems like the app gets rerendered multiple times.