I have a reactjs page, after a server call, the value of a variable called image never updates to the HTML display. I have the server call and the HTML elements rendered all in one page of .jsx Here is a snippet:
var makeServerCall = {
method: 'GET',
url: 'http://localhost:'+id,
headers: {
'Content-Type': 'application/json'
},
json: true
};
axios(makeServerCall)
.then((response) => {
image = response.data;
})
.catch((error) => {
alert(error)
})
when I try to retrieve the value of image from server call, although it prints to the console but the value of the HTML never updates
return (
....
<Avatar src={image ? `data:image/jpeg;base64,${image}` : ''}/>
....
);
I have a reactjs page, after a server call, the value of a variable called image never updates to the HTML display. I have the server call and the HTML elements rendered all in one page of .jsx Here is a snippet:
var makeServerCall = {
method: 'GET',
url: 'http://localhost:'+id,
headers: {
'Content-Type': 'application/json'
},
json: true
};
axios(makeServerCall)
.then((response) => {
image = response.data;
})
.catch((error) => {
alert(error)
})
when I try to retrieve the value of image from server call, although it prints to the console but the value of the HTML never updates
return (
....
<Avatar src={image ? `data:image/jpeg;base64,${image}` : ''}/>
....
);
Just create one state for handling the image data.I give the sample one. Hope this will work
const App=()=>{
const [image,setImage]=useState(null);
const makeServerCall =()=>{
axios.get(`http://localhost:${data.id}`, {
headers: {
'Content-Type': 'application/json'
}
}).then((res) => {
setImage(res.data);
}).catch((error) => {
console.log(error)
});
useEffect(()=>{
makeServerCall();
});
console.log(image);
return (
....
<Avatar src={image ? `data:image/jpeg;base64,${image}` : ''}/>
....
);
}
Is there a state update? If there is no state update react will not rerender and hence the updated value will not be "seen" by React or "used" by DOM.
useState
const [image,setImage] = useState("defaultImageUrl");
const makeServerCall = {
method: 'GET',
url: 'http://localhost:'+id,
headers: {
'Content-Type': 'application/json'
},
json: true
};
axios(makeServerCall)
.then((response) => {
image = response.data;
setImage(image);
})
.catch((error) => {
alert(error)
})
/**
makeServerCall();
**/