trying to get random gifs at onClick from GIFs API

Viewed 472

I am trying to display random gifs at onClick from GIFs API, but I am getting an error:

'Cannot read property 'images' of undefined'

when trying to get the URL for images.

Additionally, I have created a handleClick function to get random GIFs on every click.

Main.js

const Main = () => {
    const [data, setData] = useState([])

     useEffect(() => {
        fetch('https://api.giphy.com/v1/gifs/trending?&limit=9&api_key=aIINKf0Pxb8MDhC2QPzTLbgvUXN6Uz7l')
        .then(response => response.json())
        .then(responseData => setData(responseData.data))
        .catch(error => {
            console.log('Error fetching and parsing data', error)
          })
    },[])
    
    return(
        <div className="main hide">
            <GifList data={data} />    
        </div>
    )
}
export default Main

GifList.js

import Gif from './Gif'

const GifList = (props) => {

    let results = props.data
    let gif

        const pickRandomGif = () =>{
        let randomGifs = []

        for(let i=0; i<9; i++){
            let randomNumber = Math.floor(Math.random() * results.length)   
            randomGifs.push(randomNumber)
        }
        
        gif = randomGifs.map(random => 
            <Gif url={!results ? 'Loading...' : `${results[random].images.fixed_height.url}`} 
                 key={random.id} />
        )
    }

        const handleClick = (e) =>{
           e.preventDefault()
           pickRandomGif()
        }

        return (
            <div>
                <ul className="gif-list">
                    {gif}
                </ul>
                <button className="btn" onClick={handleClick}>Click here</button>
            </div>
         )
    }
export default GifList

Gif.js

const Gif = (props) => {
    return (
    <li className="gif-wrap">
        <img src={props.url} alt=""/>
    </li>
    )
  }
export default Gif;
1 Answers

When the data is loading, data (and thus results) is an empty array. In your GifList, when data is empty randomNumber always equals 0. Then, when you map the randomGifs array, you try to access results[0], which is undefined since results is empty. This causes the error, since undefined is not an object with property images.

You should add a check for whether results is empty (or whether results[random] is undefined) to solve the issue.

Related