Home > OS >  xxxx.map is not a function in nodejs
xxxx.map is not a function in nodejs

Time:04-04

I have api call which works fine but sometimes (most of the times it doesn't) it returns response.data.result.map is not a function and result is, it jumps out of my app (stopping the app).

Here is sample of my returned data:

data {
  status: '1',
  message: 'OK',
  result: [
    {..},
    {...}
  ]
}

here is my function

await axios.get(url).then(async (response) => {
    console.log('data', response.data); // sample data above
    response.data.result.map(async (item) => {
        //...
    });
});

Because it just happens sometimes and not always I was wonder it might be issue of api provider that can't process requests or any other reason (not sure about this thought though).

Any suggestion to avoid that error and my app being stopped?

CodePudding user response:

The issue indicates that the result property is a data structure that does not have the map function usually not an array-like, it can be either undefined or a string.

One thing I can suggest is to verify that the property is actually an array before start accessing like:

if ( response.data.result && Array.isArray( response.data.result ) ) {
    response.data.result.map() 
} else { 
    console.log( response );
}

Looks like the API might be returning a different value when calling it it might be an error in case you are calling the API too often, that's why I suggest outputting the whole response in the example above so you can debug this problem with more information in hand.

  • Related