admin管理员组文章数量:1305501
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}` : ''}/>
....
);
Share
Improve this question
edited Feb 4 at 10:26
Learner
asked Feb 4 at 10:09
LearnerLearner
831 silver badge14 bronze badges
2 Answers
Reset to default 2Just 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.
- Put image in a state variable
- use
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();
**/
本文标签: javascriptupdate a variable after a server call using axios reactjsStack Overflow
版权声明:本文标题:javascript - update a variable after a server call using axios reactjs - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741774945a2396967.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论