简体   繁体   中英

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;

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} />}
    </>
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM