Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

xxxx.map is not a function in nodejs

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading