score:-1

i have found the answer. here it is:

working with the fetch api - google docs

score:0

 var myheaders = new headers();
 myheaders.append("response", "image/jpeg");
 myheaders.append("psid", "");
 myheaders.append("x-api-key", "z7dwtzhqrklch7bvswqhnrdtpzilblys");
 myheaders.append(
    "authorization",
    "bearer token"
 );

var raw = "";

var requestoptions = {
  method: "get",
  headers: myheaders,
  //body: raw,
  redirect: "follow",
};
let response = await fetch(
  "yoururl",
  requestoptions
)
.then((response) => response)
.then((result) => result)
.catch((error) => console.log("error", error));

 res = await response.blob();

then in image tag in your html or jsx file you can do it as follows:

 <img src={window.webkiturl.createobjecturl(res)} />

score:5

this is my tried and tested method for fetching data:

componentdidmount(){
    fetch('https://www.yoursite.com/api/etc', {
      method: 'get',
      headers: {
        'accept': 'application/json',
        'content-type': 'application/json',
      },
    })
    .then((response) => {
      return response.text();
    })
    .then((data) => {
      console.log( json.parse(data) )
      this.setstate{( pic: json.parse(data) )}
    })
}

then within your img

src={ this.state.pic }

score:7

i was able to render images from a backend call in react using a pattern similar to this using: react hooks, axios, and url.createobjecturl

i used the url.createobjecturl(blob) method and used the axios configuration { responsetype: 'blob' } to make sure the the data type would fit.

const imagecomponent = (imageids) => {
  const [images, setimages] = react.usestate([])

  react.useeffect(() => {
    async function getimage (id) {
      let imageblob
      try {
        imageblob = (await axiosclient.get(`/api/image/${id}`, { responsetype: 'blob' })).data
      } catch (err) {
        return null
      }
      return url.createobjecturl(imageblob)
    }
    async function getimages () {
      const imagearray = []
      for (const id of imageids) {
        imagearray.push(await getimage(id))
      }
      setimages(imagearray)
    }

    getimages()
  }, [imageids])

  return images.map((img, i) => {
    return <img src={img} alt={`image-${i}`} key={i} />
  })
}

[edit]: if your api is a protected route just make sure your axios http client is initialized with the token already


Related Query

More Query from same tag