-1

I make an api call to an endpoing and inside the apiFetch I get a value. I want to display this value from outside the function but it doesn't get updated. Any ideas why it does this?

save: () => {
          var newValue="default";
          apiFetch( { path:'/url', } ).then( res => {
          newValue = (res[0].value);

          // this shows the new value
          console.log(newValue);

      } );
      //this shows "default"
      return <p>{newValue}</p>
    }
Jay ww
  • 1

2 Answers2

0

Your function is asynchronous, you can use async/await

save: async () => {
  const response = await apiFetch( { path:'/url', } );
  const newValue = response[0].value;
  console.log(newValue);
  return <p>{newValue}</p>
}

Then, inside your caller block:

const newValueParagraph = await yourobject.save();
Wojtek
  • 191
  • 9
0

It looks like you need to return your Promise. Right now you make the async request to the api, and while that's doing it's thing you return newValue which is still just 'default.

Try like this:

save: () => {
  var newValue = "default";
  return apiFetch({ path: '/url', }).then(res => {
    newValue = (res[0].value);

    // this shows the new value
    console.log(newValue);
    return <p>{newValue}</p>
  });
}
spirift
  • 2,136
  • 11
  • 16