React : How to use the result of an API call, in my JSX? (scope problem)

Advertisements

I’m trying to use the result of my API call (response) to display it in my JSX at src level.

But because of the scope, I don’t have access to "response". I tried declaring response as an empty variable in global scope before assigning it in my useEffect, but it doesn’t work.

useEffect(() => {
    const toFetchProfilPicture = async () => {
      try {       
        const response = await axios.get(
        `http://localhost:4200/api/user/image/${JSON.parse(localStorage.getItem("user")).user_id}`
          );
      } catch (err) {
        throw err;
      }
    };
    toFetchProfilPicture();
  }, []);


  return (
    <div className="modal">
      <form className="modal__infos" onSubmit={saveChange}>
        <div className="modal__photo"> 
          <img src={response.data[0]} alt="profile_picture" />
        </div>
      </form>
    </div>
  );
};

I could not use a function to have "response" in the global scope, but I would like to do otherwise.

How do I use "response" in my JSX?

>Solution :

You should use a state variable containing a string (the image URL):

const [imgSrc, setImgSrc] = useState('');

useEffect(() => {
    const toFetchProfilPicture = async () => {
      try {       
        const { data } = await axios.get(
        `http://localhost:4200/api/user/image/${JSON.parse(localStorage.getItem("user")).user_id}`
          );

          setImgSrc(data[0])
      } catch (err) {
        throw err;
      }
    };
    toFetchProfilPicture();
  }, []);


  return (
    <div className="modal">
      <form className="modal__infos" onSubmit={saveChange}>
        <div className="modal__photo"> 
          <img src={imgSrc} alt="profile_picture" />
        </div>
      </form>
    </div>
  );
};

Leave a ReplyCancel reply