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;