Home > Blockchain >  Can't get image to load after connecting to an API using react.js
Can't get image to load after connecting to an API using react.js

Time:02-24

I've created a custom fetch component, and I'm simply trying to get an image to load on the page from an API called "the dog API". Have I missed something crucial?

App.js

import './App.css';
import './Dog.js';
import useFetch from './useFetch';


function DogApp() {

  const API_KEY = "";
  const { data, loading, error } = useFetch(`https://api.thedogapi.com/v1/images/search/API_KEY=${API_KEY}`);


  if (loading) return <h1>Loading the dogs!</h1>

  if (error)console.log(error);

  return (
    <div className="DogApp">
      <img src={data?.url}></img>
    </div>
  );
}

export default DogApp;

UseFetch.js (hook for fetching the data)

import { useEffect, useState } from 'react';
import axios from "axios";

function useFetch(url) {

    const [data, setData] = useState(null);    //initialize as null depending on what data is
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);

    useEffect(() => {
        setLoading(true);
        axios                      //make request, if successful it sets data, if not, seterror state
            .get(url)
            .then((response) => {
                setData(response.data);
            }).catch((err) => {
                setError(err)

            }).finally(() => {
                setLoading(false);

            });
    }, [url]);

    return {data, loading, error}; 

}

export default useFetch;

API URL I'm trying to retrieve data from : https://api.thedogapi.com/v1/images/search/

CodePudding user response:

So you're API call (according to the example on thedogapi.com) requires the API key to be set in the header like so:

axios.defaults.headers.common['x-api-key'] = "DEMO-API-KEY"

That fixes the 404, but your code still won't work because the data is returned as an array of objects. So you'll need to map them like so:

{data.map((breed) => (<img src={breed?.url} />))}

I've created a demo sandbox here

  • Related