skip to Main Content
import React, { useState } from 'react'
import './App.css'

function Dog(data) {
    const [url, setUrl] = useState('')

    function fecth_data() {
        fetch('https://dog.ceo/api/breeds/image/random')
            .then((res) => res.json())
            .then((data) => setUrl(data))
        console.log(data)
    }
    return (
        <div className="dog-main">
            <img src={url} className="dog-random" alt="a dog" />
            <button className="dog-btn" onClick={fecth_data}>
                {' '}
                Generate!{' '}
            </button>
        </div>
    )
}

export default Dog

I cannot fetch my dog api can someone please help? I am new at react whatever I do it doesn’t help. Pictures don’t come to the screen

2

Answers


  1. You need to call fecth_data() in useEffect.

     useEffect(() => {
        fecth_data()
      }, [])
    Login or Signup to reply.
  2. Your api endpoint returns a json object with keys message and status, you are setting your src to that, and the <url> tag does not understand that. It needs a string, so you can take that returning object and set the url to your returned data.message.

    import React, { useState } from 'react'
    
    function Dog(data) {
        const [url, setUrl] = useState('')
    
        function fetch_data() {
            fetch('https://dog.ceo/api/breeds/image/random')
                .then((res) => res.json())
                .then((data) => {
            console.log(data)
                  setUrl(data.message)
                })
        }
        return (
            <div className="dog-main">
                <img src={url} className="dog-random" alt="a dog" />
                <button className="dog-btn" onClick={fetch_data}>
                    Generate!
                </button>
            </div>
        )
    }
    
    export default Dog
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search