1

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>
)
Karan Kiri
  • 316
  • 2
  • 12
EGarcia
  • 17
  • 6

3 Answers3

0

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).

ApplePearPerson
  • 4,209
  • 4
  • 21
  • 36
0

This

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

should be

setGifLinks(gifLinks.data[0].url)
kiranvj
  • 32,342
  • 7
  • 71
  • 76
  • It seems like this should work (even though console logging gifLinks still shows as an object, although the inspection shows the src as the link) but there's a CORB error. – EGarcia Oct 17 '19 at 20:38
  • 1
    Edit to the previous comment: It worked, had to change the property path, the one I was using was the wrong one. It's actually "gifLinks.data[0].images.fixed_height.url". Whoops! – EGarcia Oct 17 '19 at 20:45
0

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" />
norbitrial
  • 14,716
  • 7
  • 32
  • 59
  • I tried this and still nothing. When I console logged gifLinks.url it shows up as undefined. Plus there's a CORB error now. – EGarcia Oct 17 '19 at 20:35