skip to Main Content

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.

2

Answers


  1. Having a form will make your page reload. By removing it you can make it work.
    If you still need to have the form and do the things you can try like this.

        <form onSubmit={(e)=>e.preventDefault()}>
               // ..... form content inside ...
       </form>    
    
    Login or Signup to reply.
  2. <button onClick={getAMeme}>Generate Meme</button>
    
    const getAMeme = (e) => {
        e.preventDefault()
        const randomNum = Math.floor(Math.random() * meme.length)
        const url = meme[randomNum].url
        console.log(url)
        setUrl(prevUrl =>({
            ...prevUrl, 
            randomImage: url
        }))
       
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search