0

JS newbie here. I would like to store the JSON data from an API call inside a variable in my .fetch method.

Here is my current code:

// Store database to array
let database = []

fetch('./database.json')
.then(response => response.json())
.then(data => console.log(data))

The data is being logged in the console succesfully, but I would like for them to be saved inside the database array.

Any idea how I would go about that? Thank you all so much!

skubri
  • 109
  • 4
  • `.then(data => { database.push(data); })`. Future code, to wait for the result, either needs to continue to chain `.then()`, or use `async`/`await` syntax to wait for it. Javascript code does NOT execute top to bottom when asynchronous code is involved. To make future code wait for async calls, you have to introduce more promise chaining with .then(), or the syntactic sugar for it `async`/`await` – Andy Ray Mar 18 '21 at 18:52

2 Answers2

0

Sure, have your code changed to the following:

// Store database to array
let database = []

fetch('./database.json')
.then(response => response.json())
.then(data => {
    database.push(data)
    console.log(database)
})

I hope this solves your problem.

Mpenyana
  • 9
  • 2
  • Hey thanks for the answer. It seems that if I try to console log an element of the database array after storing the data that way I get undefined. For example if I do console.log(database[0]) it returns undefined, but if I do it using data[0] inside of .then it returns correctly. – skubri Mar 18 '21 at 18:47
  • @Mypenyana please remove this answer, you aren't familiar with async code in Javascript – Andy Ray Mar 18 '21 at 18:51
  • Do you mind sharing the url your making the API call to? – Mpenyana Mar 18 '21 at 18:51
0

As fetch call is async database will always be [] till the api call is resolved in case you plan to assign data to database.

You can use Callbacks, Promises or async-await for dealing with async calls

Reference link - https://dmitripavlutin.com/javascript-fetch-async-await/

  • Should I just run my code inside the .then method instead of trying to store the data inside an array outside of the .then or is that bad practice? – skubri Mar 18 '21 at 19:01
  • fetch internally returns a Promise on which we invoke the .then method, you can carry out the required data assignment/processing safely in the .then method but please be aware that the set of code in .then would be executed later point in time only when the api return success. – navintellis Mar 18 '21 at 19:24