-1

Good morning, I'm developing an application and I need the images that are loaded inside a map, have an authentication header in their request. For that I build a function that does this via xhr, but as the function is asynchronous, the request is made but nothing appears on screen.

function returnImageURL(assetID){
        var xhr = new XMLHttpRequest();
        xhr.responseType = 'blob';
        xhr.onreadystatechange = function () {
            if (xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
                return URL.createObjectURL(xhr.response);
            }
        };
        xhr.open('GET', 'http://' + ocaURL + "/cover/" + assetID, true);
        xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem("session"));
        xhr.send();
    }
    return (
        <>
        { response.length !== [] ?
        <Container>
            <Contents>
        { response.map(function(content){
         return(<ContentBox key={content.idContent}>
                    <ContentImage onClick={() => {startPlay(content.idContent)}} src={returnImageURL(content.cover)}></ContentImage>
                    <ContentText>{content.nome}</ContentText>
                </ContentBox>);
            })}
            </Contents>
        </Container>
        : <TextWarm>A carregar...</TextWarm> }
        </>
    );

Attempted comment but still not working. Now he made several requests.

const [imageUrl, setImageURL] = useState('');
...
function returnImageURL(assetID){
    var xhr = new XMLHttpRequest();
    xhr.responseType = 'blob';
    xhr.onreadystatechange = function () {
        if (xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
            return URL.createObjectURL(xhr.response);
        }
    };
    xhr.open('GET', 'http://' + ocaURL + "/cover/" + assetID, true);
    xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem("session"));
    xhr.send();
}
return (
    <>
    { response.length !== [] ?
    <Container>
        <Contents>
    { response.map(function(content){
        setImageURL(returnImageURL(content.cover));
     return(<ContentBox key={content.idContent}>
                <ContentImage onClick={() => {startPlay(content.idContent)}} src={imageUrl}></ContentImage>
                <ContentText>{content.nome}</ContentText>
            </ContentBox>);
        })}
        </Contents>
    </Container>
    : <TextWarm>A carregar...</TextWarm> }
    </>
);
tomas
  • 339
  • 1
  • 2
  • 14
  • Use can you use the useState hook .... When you you get results just call the set.. method to update your component – Sanmeet Dec 17 '21 at 12:42
  • Yes, I've already thought about that, but won't that make everyone end up with the same image in the end? Because it would just be a useState that would be updated. – tomas Dec 17 '21 at 12:45
  • https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call – epascarello Dec 17 '21 at 12:54

1 Answers1

0

The idea for xhr or a fetch request to fetch data is that , when the request is finished and we have the required data then we can update the component with the fetched data. [ you can use this with useEffect hook used for fetching data initially in most cases :-)]

import { useState } from "react";

const MyComp = ()=>{
 
  const [myArray , setArray] = useState([]);
  
  const myXhr =  async ()=>{
    const data =  await fetch("...url");
    const fetchedData = await data.json();
    // checking if response was a success
    if(fetchedData.error){
      throw new Error("Something went wrong");
    }else{
      setArray(fetchedData.myArray);
    }
  }
  
  return (
    <React.fragment>
       {
         myArray.length > 0 ?
        myArray.map((item , index ) => 
         <div className="success" key={index}>
            Success Code 
         </div>
        )
         : 
         <div>Fetching ?...</div>
       }
    </React.fragment>
    )
}

export default MyComp;
Sanmeet
  • 1,191
  • 1
  • 7
  • 15
  • Here you can get the data when the function is invoked or called like on button click or else use useEffect hook with options as an empty array so it doesn't loads the again after state changes of any var ! – Sanmeet Dec 17 '21 at 12:53