Save a react axios response of a .jpg into state then display that image from state

How can I save the response data into state first directly from any .jpg link then load that image into the img tag.

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

const ProfileImage = () => {

  const [profileImage, setProfileImage] = useState();
  const [loading, setLoading] = useState(true);
  
  const getUserImage = async () => {
    let res = await axios({
      method: 'get',
      url: `https://st.depositphotos.com/1937573/2310/i/600/depositphotos_23101854-stock-photo-handsome-man-outdoor.jpg`
    });
    setProfileImage(res.data);
    setLoading(false);
  }
  
  useEffect(() => {
    getUserImage();  
  }, []);

  return (
      {loading && <div>loading...</div>}
      {!loading && <img src={profileImage} />}
  )
};

export default ProfileImage;

Answer

You need to read get the response as blob. So use responseType: "blob", Once you have the blog use FileReader to convert it to image data.

Your full code will look like below. See the working version here

import "./styles.css";
import axios from "axios";
import { useEffect, useState } from "react";

export default function App() {
  const [profileImage, setProfileImage] = useState();
  const [loading, setLoading] = useState(true);

  const getUserImage = async () => {
    let res = await axios({
      method: "get",
      responseType: "blob",
      url: `https://st.depositphotos.com/1937573/2310/i/600/depositphotos_23101854-stock-photo-handsome-man-outdoor.jpg`
    });
    let reader = new window.FileReader();
    reader.readAsDataURL(res.data);
    reader.onload = function () {
      let imageDataUrl = reader.result;
      //console.log(imageDataUrl);
      setProfileImage(imageDataUrl);
      setLoading(false);
    };
  };

  useEffect(() => {
    getUserImage();
  }, []);

  return (
    <>
      {loading && <div>loading...</div>}
      {!loading && <img width="100" alt="" src={profileImage} />}
    </>
  );
}

Leave a Reply

Your email address will not be published. Required fields are marked *