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> }
</>
);