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 Image src undefined – AWS S3

I have a:

<img src={ "http://127.0.0.1:5001/api/users/profile_photo/" + user.profile_photo }
     className="img-fluid rounded-circle"
     alt="rounded image"/>

Whenever I load in the page, the function getUser() runs and retrieves the user.

const getUser = async () => {
  let user = await axiosWithAuth().get('/users/' + userId);
  setUser(user.data);
};

user.profile_photo is the key that I get back from AWS s3. ex. 43256722324654

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

The Problem:
When the page loads, the image src is not yet set from what it looks like because, in the express backend, the profile_photo comes through undefined. It becomes defined on the second go around.

Because of this AWS throws an error for noSuchKey

/Users/timbogdanov/Desktop/hlam/server/node_modules/AWS-SDK/lib/request.js:31
throw err;
^

NoSuchKey: The specified key does not exist.

Is there any way to stop the image from sending the get request until the user state object is set?

Thank you!

>Solution :

Add a condition to render the image. If user.profile_photo is not defined don’t render it.

{user.profile_photo && <img src={ "http://127.0.0.1:5001/api/users/profile_photo/" + user.profile_photo }
     className="img-fluid rounded-circle"
     alt="rounded image"/>
}
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