Problem with $ .getJSON.then ()


I do a data extraction with $ .getJSON () without problems, I get what I want from my database and then I work with .then but in this line

getKeys().then(data => => keys.push(key)));

that I keep in my variable 'keys' which is an array but when I open it in the browser I see it by console and it comes out like this [], I click and it unfolds in this way


and the array remains as an object type, preventing me from mapping it, how can I make it mappable without having to do this.setState () in React? (with mappable I mean ())

asked by Orlando Andaur 15.03.2017 в 20:24

2 answers


I already solved it with this:

getKeys().then(data => this.setState({ keys : data.filter(info => info.keygen == key) }))

The idea is that it does not reveal all the keys to me but only reveals the one that was selected, that's why I filtered it with respect to what was sent. Greetings and thanks for the answers.

answered by 16.03.2017 в 02:40

You are using promises. The promises are executed asynchronously, so if you try to access 'keys' outside of the promise, probably the line where you print the content will run before the promise itself, therefore it will print an empty array but when you inspect the object in the debugger you will surely see that it is already full of values, this because the asynchronous code is probably only out of phase by thousandths.

If you print keys in this way

getKeys().then(data => => keys.push(key))); // asincrono

the second line will be executed before the promise, to work with the values of the promise and to change the state of the React component, you must change the state at the end of the execution of the promise, this is achieved by doing it within the chain of promises, not outside.

    .then(data => { => keys.push(key));
        return keys;
    .then(keys => {
        ... alguna logica extra
        this.setState({keys: keys})

On the last part the variable 'keys' is still an array, it is not an object.

to work with asynchronous code you can also use async / await which also involves promises

answered by 15.03.2017 в 22:28