Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
  );
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading