Home > front end >  How to fetch images from slow API in React.js and Typescript and axios
How to fetch images from slow API in React.js and Typescript and axios

Time:11-04

I want to fetch an image url to use as the value for the src tag

            <img
              src={getAircraftImage(foundFlight.aircraft.reg)}
              alt="Aircraft"
              className="rounded-md w-24 h-12"
            />
function getAircraftImage(reg: string | undefined): string {
  let imageUrl;
  const options = {
    method: "GET",
    url: `https://aerodatabox.p.rapidapi.com/aircrafts/reg/${reg}/image/beta`,
    headers: {
      "X-RapidAPI-Key": "6445ce28c1msh4b2afb9dc1a38bbp17a68bjsn97511bcb4bbf",
      "X-RapidAPI-Host": "aerodatabox.p.rapidapi.com",
    },
  };

  axios
    .request(options)
    .then(function (response) {
      imageUrl = response.data.url;
    })
    .catch(function (error) {
      console.error(error);
    });

  return imageUrl;
}

Problem The Api is not that fast. When i load the image only the alt tag is shown. I have seen in multiple websites a way to show a fallback image as the request is made then show the correct image after but i dont know how to implement it. How do i accomplish that?

CodePudding user response:

As said in the comments: Just use hooks. useEffect to properly execute the request, useState to store the result and render conditionally. You may want to use this hook combination in any scenario where you need to do a request to an external API. As a code example, for a simple component:

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

const MyComponent = () => {
  // create state of loading, but also state for data
  const [loading, setLoading] = useState(true);
  const [data, setData] = useState([])

  // useEffect to execute request
  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      try {
        // gets response and saves data into 'data' state
        const {data: response} = await axios.get('/stuff/to/fetch');
        setData(response);
      } catch (error) {
        console.error(error.message);
      }
      setLoading(false);
    }

    fetchData();
  }, []);

  // conditional rendering if already loaded
  return (
    <div>
    {loading && <div>Loading</div>}
    {!loading && (
      <div>
        <h2>Doing stuff with data</h2>
        {data.map(item => (<span>{item.name}</span>))}
      </div>
    )}
    </div>
  )
}

export default MyComponent;

Source: https://dev.to/darkmavis1980/fetching-data-with-react-hooks-and-axios-114h

  • Related