Vlasta Po
Vlasta Po

Reputation: 901

Javascript Fetch API - How to save output to variable as an Object (not the Promise)

Please, how can I save output of fetch to a variable - to be able to work with it as with an object?

Here is the code:

var obj;
fetch("url", {
  method: "POST",
  body: JSON.stringify({
    "filterParameters": {
      "id": 12345678
    }
  }),
  headers: {"content-type": "application/json"},
  //credentials: 'include'
})
.then(res => res.json())
.then(console.log)

The final console.log will show an object. But when I tried to save it to variable .then(res => obj = res.json()) than the console.log(obj) will not hold the Object, but the Promise.

Console

Any idea please, how to turn it into an Object saved in the variable?

Upvotes: 65

Views: 182655

Answers (7)

Prathamesh More
Prathamesh More

Reputation: 1489

Instead of storing in a variable, create a function that will return data, and then store it in a variable. So It can accessible in your whole file.

async function fetchExam(id) {
        try {
            const response = await fetch(`/api/exams/${id}`, {
                method: 'GET',
                credentials: 'same-origin'
            });
            const exam = await response.json();
            return exam;
        } catch (error) {
            console.error(error);
        }
    }

Then call that function to get data

async function renderExam(id) {
        const exam = await fetchExam(id);
        console.log(exam);
}

Update

With the current version of Node.js v14.3.0 support Top-Level async-await

import axios from 'axios';

const response = await axios('https://quote-garden.herokuapp.com/api/v3/quotes/random');
console.log(response.data);

Running this file using node --harmony-top-level-await top-level-async-await.js

Output

{
    statusCode: 200,
    quote: {
        _id: '5db17aaeb69dc744b4e72b82',
        quoteText: 'I can take more punishment than anyone in the business.',
        quoteAuthor: 'Ric Flair',
        quoteGenre: 'business',
        __v: 0
    }
}

More details: https://medium.com/@pprathameshmore/top-level-await-support-in-node-js-v14-3-0-8af4f4a4d478

Upvotes: 30

Joe
Joe

Reputation: 559

I've done this before. It's quite simple actually. Here is how I did it with an API I sometimes use:

x = await fetch("https://api.quotable.io/random").then((res)=>res.json()).then((json)=>json.content)
console.log(x) // Returns 'The world cares very little about what a man or woman knows; it is what a man or woman is able to do that counts.'

Alternatively, you can also do:

x = fetch("https://api.quotable.io/random").then((res)=>res.json()).then((json)=>json.content)
console.log(await x) // Returns 'The world cares very little about what a man or woman knows; it is what a man or woman is able to do that counts.'

Upvotes: 0

yuriy636
yuriy636

Reputation: 11661

.json() is an async method (it returns a Promise itself), so you have to assign the parsed value in the next .then()

var obj;

fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(res => res.json())
  .then(data => {
    obj = data;
   })
  .then(() => {
    console.log(obj);
   });

Modern async/await equivalent

You have to await the .json() method.

async function foo() {
  let obj;

  const res = await fetch('https://jsonplaceholder.typicode.com/posts/1')

  obj = await res.json();

  console.log(obj)
}

foo();

Upvotes: 89

amir mohseni
amir mohseni

Reputation: 314

A simple and handy solution is :

function myFunc(success) {
//do what you want HERE.

console.log(success)

}

fetch('https://reqres.in/api/users?page=2')
    .then(data => data.json())
    .then(success => myFunc(success));

Upvotes: 4

Sam
Sam

Reputation: 761

let data = [];

async function getRandomUser(){
  // gets the response from the api and put it inside a constant
  const response = await fetch('https://randomuser.me/api');
  //the response have to be converted to json type file, so it can be used
  const data = await response.json();
  //the addData adds the object "data" to an array
  addData(data)
}

function addData(object) {
  // the push method add a new item to an array
  // here it will be adding the object from the function getRandomUser each time it is called
  data.push(object);
  //the fetched data is available only on this scope
  console.log("This is the value of date inside the function addData:")
  console.log(data)
}

//Calls the function that fetches the data
getRandomUser()

  console.log("This is the value of data outside the scope")
  console.log(data)
  

Upvotes: 4

Rasla
Rasla

Reputation: 141

You can do like this. First fetch the data and create a function to do something with the data.

And then pass the result to that function and access it anywhere.

fetch('https://pokeapi.co/api/v2/pokemon/ditto')
    .then(jsonData => jsonData.json())
    .then(data => printIt(data))

let printIt = (data) => {
    console.info(typeof data)
}

Upvotes: 11

Shoaib Khalil
Shoaib Khalil

Reputation: 2402

Easiest approach is to use async/await method.

Simply copy & paste the following code in your chrome dev console to see the magic:

async function githubUsers() {
            let response = await fetch('https://api.github.com/users')
            let users = await response.json()
            console.log(users)
    }

githubUsers()

Upvotes: -1

Related Questions