Nazlul
Nazlul

Reputation: 1

Gif not loading in react

I tried to fetch gif from giphy using API, bu[enter image description here][1]t the gif does not load

useFetch.jsx

import { useEffect, useState } from 'react';

const API_KEY = import.meta.env.VITE_GIPHY_API;

const useFetch = ({ keyword }) => {
const [gifUrl, setGifUrl] = useState("");


const fetchGifs = async () => {
    try {
        const response = await fetch(`https://api.giphy.com/v1/gifs/search?api_key=${API_KEY}&q=${keyword.split(" ").join("")}&limit=1`);
        const { data } = await response.json();  ;
        setGifUrl(data[0]?.images?.downsized_medium.url);
    } catch(error) {
    setGifUrl("https://metro.co.uk/wp-content/uploads/2015/05/pokemon_crying.gif?quality=90&strip=all&zoom=1&resize=500%2C284");
    }
};

useEffect(() => {
    if(keyword) fetchGifs();
}, [keyword]);

return gifUrl;
};

export default useFetch;

How I've imported and implemented

import useFetch from '../hooks/useFetch';

const TransactionCard = ({ addressTo, addressFrom, timestamp, message, keyword, amount, 
url }) => {
const gifUrl = useFetch({ keyword });
console.log("GIF URL:", gifUrl);
console.log("Fallback URL:", url);
return (.....
      .........
<img 
    src = {gifUrl || url}
    alt ="gif"
    className='w-full h-64 2xl:h-96 rounded-md shadow-lg object-cover'
    onError={(e) => {
    console.error("Error loading image:", e);
    }}
 />
 ......

I tried to console.log the url and it shows undefined

Upvotes: 0

Views: 65

Answers (0)

Related Questions