-1

I'm fetching data from a Rest API, which returns me an Object with an Array of results. When I try mapping through it, it gives me the following error:

TypeError: Cannot read property 'results' of undefined

function Teste() {
    let results;
    fetch('https://parseapi.back4app.com/classes/MyClass', {
        method: 'GET',
        headers: {
            'X-Parse-Application-Id': 'MyKey',
            'X-Parse-REST-API-Key': 'MyKey',
            'X-Parse-Master-Key': 'MeyKey'
        }
    }).then(response => {
        return response.json();
    }).then(data => {
        results = data;
        console.log(results);
    }).catch(error => {
        console.log(error);
    });

    const mapCats = Object.keys(results.results).map(key => 
        <li key={key}>{results.results[key].name}</li>
    );

    return (
        mapCats
    );
}

The output of the results is this:

{
    "results": [
        {
            "objectId": "JoT2miD1vo",
            "name": "Mercado",
            "createdAt": "2018-11-08T13:49:25.600Z",
            "updatedAt": "2018-11-08T13:50:08.721Z"
        },
        {
            "objectId": "DEuZHY7BwY",
            "name": "Panificadora",
            "createdAt": "2018-11-08T13:49:40.385Z",
            "updatedAt": "2018-11-08T17:06:09.129Z"
        },
        {
            "objectId": "V3g1FXNtLK",
            "name": "Farmácia",
            "createdAt": "2018-11-08T13:50:02.293Z",
            "updatedAt": "2018-11-08T13:50:02.293Z"
        },
        {
            "objectId": "Psl9GWqB4F",
            "name": "Loja",
            "createdAt": "2018-11-08T13:50:34.696Z",
            "updatedAt": "2018-11-08T13:50:34.696Z"
        },
        {
            "objectId": "ezlncu6cd1",
            "name": "Lanchonete",
            "createdAt": "2018-11-08T13:50:41.649Z",
            "updatedAt": "2018-11-08T13:50:41.649Z"
        },
        {
            "objectId": "vDgxIW69rr",
            "name": "Sorveteria",
            "createdAt": "2018-11-08T13:50:54.824Z",
            "updatedAt": "2018-11-08T13:50:54.824Z"
        },
        {
            "objectId": "VdxckEDG7q",
            "name": "Food Truck",
            "createdAt": "2018-11-08T13:51:14.096Z",
            "updatedAt": "2018-11-08T13:51:14.096Z"
        },
        {
            "objectId": "LHrGCT9SCs",
            "name": "Pizzaria",
            "createdAt": "2018-11-08T16:12:48.317Z",
            "updatedAt": "2018-11-08T16:12:48.317Z"
        }
    ]
}

When I declare this object as a constant in my code, it returns me no errors and the mapping works. But when I try assigning the results of data it won't work.

Guilherme P.
  • 113
  • 9
  • because you use the varaible before it is set.... – epascarello Nov 16 '18 at 15:43
  • @epascarello how so? Do I need to wait for it to be assigned an then make a callback? – Guilherme P. Nov 16 '18 at 15:44
  • Because the fetch call is asynchronous so that code fires AFTER you run the map line. That is why fetch has promises. The code would have to run in the then, but you would not be able to return it. https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron – epascarello Nov 16 '18 at 15:45
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – ponury-kostek Nov 16 '18 at 15:45

1 Answers1

2

To do this correctly you should call setState() in the promise chain.

.then(data => {
    results = data;
    this.setState({results});
    console.log(results);
}

Then you can create the <li> elements in render():

render() {
    const mapCats = Object.keys(this.state.results.results).map(key => 
        <li key={key}>{this.state.results.results[key].name}</li>
    );

    // ...
}

Note that I am assuming the function that calls fetch() is inside your class. You can do what you want with a global function, but it is a little more complex. The basic idea is the same, though.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
  • That worked. I changed my function to a class, added an empty Array do my state and passed my results to it. Thanks. I'm just waiting until I can mark your answer as the correct one. – Guilherme P. Nov 16 '18 at 15:55
  • @GuilhermeP. Glad to hear that you filled in the details missing from my answer. – Code-Apprentice Nov 16 '18 at 17:30