Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store fetch response in javascript variable

sorry for the basic question. I was trying using fetch to get data from api and want to store that response into a javascript variable but its not working as I have expected My code-

async function fun() {
    var a = "initial";
    fetch('https://jsonplaceholder.typicode.com/todos/1')
        .then(res => res.json())
        .then(data => {
            a = data;
            console.log(a);
        })

    await console.log("Response => ", a);
}

Output - Response => initial

What is the correct way of doing this.

like image 804
Amara Avatar asked Jun 03 '26 19:06

Amara


2 Answers

You are doing more than you need to. Your fetch call should be returning the promise. Then when you want to access the data, you await the fun call, and can read the response

async function fun() {
  return fetch('https://jsonplaceholder.typicode.com/todos/1').then(res => res.json());
}

const data  = await fun();

Alternatively, if you wanted to just use async/await you could do something like

const fun = async () => {
  const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
  return response.json()
}

await fun();
like image 127
Andrew Avatar answered Jun 06 '26 08:06

Andrew


You may need to add await before fetch.

async function fun() {
  var a = "initial";
  await fetch('https://jsonplaceholder.typicode.com/todos/1')
    .then(res => res.json())
    .then(data => {
      a = data;
      console.log(a);
    })

  console.log("Response => ", a);
}
like image 33
Caulic Avatar answered Jun 06 '26 09:06

Caulic