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
Add a comment  | 

2 Answers 2

Reset to default 2

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.

  1. Put image in a state variable
  2. 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