Search code examples
javascriptreactjsfetch

Displaying images from a URL in React


I'm trying to load user avatars from a S3 bucket where on making a GET request to /uploads/resume/{user_uid} a URL is returned with the image. This is how my request looks like

const getAvatar = async() => {
    var myHeaders = new Headers();
    myHeaders.set('Authorization', 'Basic ' + credentials);
    var requestOptions = {
      method: 'GET',
      headers: myHeaders,
      redirect: 'follow'
      };
     
      let response;

      try {
          response = await fetch (`${APIlink}/uploads/resume/${user_uid}`, requestOptions)
      } catch (err) {
          console.log("Failed");
          return;
      }
      const result = await response.text();
      setAvatarURL(result);
      console.log(avatarURL);

  };

Then I do

<img src={avatarURL}/>

in my render method to display the avatar of a user but nothing is displayed. On doing inspect element on the image tag I see the URL with an extra pair of double quotes something like this <img src=""URL""> avatarURL should be a string only then why is there an extra pair of quotes?

Doing console.log(avatarURL); gives me something like this "https://i*******-s3uploadbucket-119b74g6cdo0z.s=host"


Solution

  • Try it like this :

    <img src={avatarURL.replace(/['"]+/g, '')}/>  // to remove extra double quotes