Search code examples
javascriptreactjsreact-hooksgiphy-api

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

Solution

  • This

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

    should be

    setGifLinks(gifLinks.data[0].url)