-1

I have been trying to think of a way to store the data received in Line 1 (mentioned in comments) in to a variable that I can modify later on.

var requestOptions = {
    method: 'GET',
    redirect: 'follow'
};

fetch("https://api.covid19api.com/live/country/south-africa", requestOptions)
    .then(response => response.text())
    .then(result => console.log(result)) //Line 1
    .catch(error => console.log('error', error));
Peyman Mohamadpour
  • 17,954
  • 24
  • 89
  • 100
Adi
  • 1
  • 4
  • 1
    You can just do `.then(result => myVariable = result)`, however [beware as this is async code](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron). You are better off [working with the asynchronicity](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call). – VLAZ May 20 '20 at 06:55
  • 1
    Does this answer your question? [return value after a promise](https://stackoverflow.com/questions/22951208/return-value-after-a-promise) – jonrsharpe May 20 '20 at 08:54

1 Answers1

-2

You can store responses to another variable like this.

but You should use that with async/await because fetch() is async.

var requestOptions = {
  method: 'GET',
  redirect: 'follow'
};

async function fetchData(){
  const response = await fetch("https://api.covid19api.com/live/country/south-africa", requestOptions)
  .then(response => response.text())
  .then(result => { return result }) //Line 1
  .catch(error => console.log('error', error));

   //console.log(response); //store in response.
}

fetchData();
kyun
  • 9,710
  • 9
  • 31
  • 66
  • I am storing it in a variable by using myVariable = fetchData(). This stores data in myVariable no doubt but it also prints it out on the console which I do not want. Is there a way we can do that? – Adi May 20 '20 at 07:25
  • @Adi I edited the answer. and If you don't want to see `console.log`, you can erase that. – kyun May 20 '20 at 07:37
  • thanks but I am facing 1 more issue. Can you please have a look at https://stackoverflow.com/q/61908410/13579522 – Adi May 20 '20 at 08:29
  • @jonrsharpe so what should I do? – Adi May 20 '20 at 08:33
  • jonsharpe, as you can see @zynkn, has used await in his solution but It makes no difference – Adi May 20 '20 at 08:34
  • That's because they don't actually return the response they awaited, and are using `.then`/`.catch` anyway making the use of `async` largely pointless. It's not a useful answer, it's not clear why you've accepted it. – jonrsharpe May 20 '20 at 08:38
  • I am a little confused here. I don't exactly know what to do now. Can you please look at https://stackoverflow.com/q/61908410/13579522 and make changes to the code such that the edited one does not give me [object promise] and instead gives me the right value – Adi May 20 '20 at 08:41