Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

224
Views
How to store JSON in variable from fetch API

I can't disclose the URL and what API I'm using because it breaches my work's policy but hopefully, I can provide enough information for assistance. I have a JavaScript function that runs on an on-click (I'm eventually building up a form that will make use of this fetch).

function getdata() {
let customer_po = document.getElementById("customer").value;
let access_token;
let data = {
    'grant_type': 'REDACTED'
}
let state = {
    "state": "REDACTED"
}
fetch(prod_auth, {
    method: "POST",
    headers: login_header,
    body: new URLSearchParams(data),
})
    .then(response => response.json())
    .then(result => console.log(result))
}

This works and I can access the dictionary in the console. However, when I try to use my access_token variable declared earlier in such a way:

.then(response => response.json())
.then(result => {access_token = result["access_token"];})

and console.log(access_token) gives undefined. I need to access this variable in my getdata() function so it can be used as a parameter in another fetch call.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

If you defined and assigned a value to a variable synchronously as you typically do, that variable is available until you leave its scope. For the purpose of this explanation (and generally), JavaScript variables are scoped to the function they run in e.g.

var myVariable = 'acb123';
console.log(myVariable); // 'abc123'

var myFunc = function() {
  var myFunctionVariable = 'def456';
  console.log(myFunctionVariable); // 'def456'
};

console.log(myFunctionVariable); // Uncaught ReferenceEError: myFunctionVariable is not defined

Since you're using promises, you're handling the result of a non-synchronous assignment via functions and the variables you use in each of those callback functions is scoped only to within those functions. While there's no issue in taking a currently scoped variable and writing it out to the console, you'll have the issue you describe when you try to use a variable that's assigned in another non-parent function. You can access the dictionary in your console because you're not actually accessing the variable at that point - you're accessing the object saved in your console.

Going back to your fetch statement, it's making an asynchronous call, so it's not even going to immediately return anything but a promise when assigned. You've already figured out that if you want to do anything with the promise result when it is populated, you need to do so in a chained .then() method. What you're trying to do is then take this asynchronous result and pass it into a variable used and called synchronously and that's not going to work.

Rather, everything you're wanting to do, you must do in subsequent then() methods:

 fetch(prod_auth, {
    method: "POST",
    headers: login_header,
    body: new URLSearchParams(data),
})
  .then(response => response.json())
  .then(result => result["access_token"])
  .then(access_token => {} //Call your next fetch method);

Especially if you're looking at doing more elaborate chains of asynchronous operations, you might also look at using RxJS to somewhat simplify mappings across different chained operations.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!