EGarcia
EGarcia

Reputation: 17

Trying to display a GIF from Giphy API using React hooks

I'm trying to fetch a GIF with the Giphy API and have it display on the page using React hooks. It's fetching an object not the url, so all the page shows is the leaf logo.

I've tried setting the state to the GIF url (as shown in code) but it still remains as the object. I tried setting the property path in the src but it doesn't allow me to iterate into the properties.

export default function Portfolio() {

   const [gifLinks, setGifLinks] = useState([])

   useEffect(() => {
        let url = "https://api.giphy.com/v1/gifs/search?api_key=My_Api_Key&q=kittens&limit=1";

        fetch(url)
            .then(response => response.json()).then(gifLinks => {
                console.log(gifLinks);
                setGifLinks({
                    gifLinks: gifLinks.data[0].url
                })
            })
    }, [])

return (
   <div>
      <img src={gifLinks} alt="gif" />
   </div>
)

Upvotes: 1

Views: 1698

Answers (3)

norbitrial
norbitrial

Reputation: 15176

The following solution will make the job for you, just make the change as below in these two lines:

// ...

const [gifLinks, setGifLinks] = useState({});

// ...

<img src={gifLinks.gifLinks} alt="gif" />

// ...

Additionally it would be nice to find better naming for the property. You are technically using the gifLinks.gifLinks in your code if you are going with the above approach. Let me suggest the next one:

const [gifLinks, setGifLinks] = useState({});

// ... 

.then(response => response.json()).then(gifLinks => {
   setGifLinks({
      url: gifLinks.data[0].url
   });
});

So you can reference as the following:

<img src={gifLinks.url} alt="gif" />

Upvotes: 0

kiranvj
kiranvj

Reputation: 34147

This

setGifLinks({
                    gifLinks: gifLinks.data[0].url
                })

should be

setGifLinks(gifLinks.data[0].url)

Upvotes: 0

ApplePearPerson
ApplePearPerson

Reputation: 4439

You're quite literally setting the gifLinks to { gifLinks: gifLinks.data[0].url } using setGifLinks, so it makes sense that you end up with an Object because thats what you're setting it to.

What you give to the setGifLinks function will be its new value so if you just want it to be the url do setGifLinks(gifLinks.data[0].url).

Upvotes: 0

Related Questions