0

I have a jsx file with code

var React = require('react');
var CreateReactClass = require('create-react-class');


var url = "192.168.1.1:8081/json";
let data = [];

fetch(url)
.then(response => response.json())
.then(result => data.push(result));

console.log(data);
console.log(data[1].name);

console.log(data); returns data but I can't seem to get any specific attributes out from it. console.log(data[1].name); just returns: TypeError: data[1] is undefined.

on the URL address I have json

[
 {
  "id": "2",
  "name": "led",
  "color": "blue"
 },
 {
  "id": "3",
  "name": "le",
  "color": "red"
  }
]

for some reason the length of my data array is 0 even after pushing json data into it.

How can I get console to log an attribute from data variable like "name":"le".

4 Answers4

3

.fetch() is asynchronous. This console.log(data) occurs before the promise is resolved (data.push(result))

fetch(url)
.then(response => response.json())
.then(result => data.push(result))
.then( () => console.log(data))

will log the data.

One possibility is to use ES7' async feature, as explained here.

Christian Benseler
  • 7,907
  • 8
  • 40
  • 71
  • Im able to get the whole json to log in to console. But im not able to get specific attributes out of that json data variable. – user9283382 Jan 29 '18 at 11:29
  • Please read about asynchronous in javascript. You can't predict the value of 'data' outside the the then, in other workds, before the promise is resolved. When fetch() is triggered, what is inside the then() happens after the console.log, is something like "another thread". – Christian Benseler Jan 29 '18 at 11:32
0

The results of the then calls for data are asynchronous.

That means that your console.log is fired when response and result are not even finished yet.

fetch(url).then(json => {
    console.log(json);
});
vonUbisch
  • 1,384
  • 17
  • 32
0

In your fetch do something like this.

fetch(url)
 .then(response => response.json())
 .then(result => {
    data = [ ...data, ...result ]; // spread the entire array;
    console.log('Result is=', data);
  });

P.S: The entire approach for your coding style is not very good. This is not how you should maintain data, the api result should be in some state variable. So the DOM can update if any changes happen to this data.

Adeel Imran
  • 13,166
  • 8
  • 62
  • 77
-1
    var React = require('react');
    var CreateReactClass = require('create-react-class');

    var url = "192.168.1.1:8081/json";
    let data = [];

    fetch(url)
    .then(response => response.json())
    .then(result => data = result);

console.log(data[1].name);
Ash
  • 120
  • 1
  • 1
  • 10