undefined is not a function (evaluating 't.map(function(t){return u(t)})')

Viewed 123

"undefined is not a function" is probably a widely asked question. But I could not find a solution to the exact problem I have here.

My code is as follows:

How I call function where problem arise:

...
service.queryListToInfoList(response.data || []);
...

In service,

export const queryListToInfoList = queryList => queryList.map(ql => queryToInfo(ql));

export const queryToInfo = query => { //some process; return {..}};

package.json

"dependencies": {
    ...
    "react": "16.5.1",
    "react-native": "^0.57.1"
    ...
 },
 "devDependencies": {
    ...
    "@babel/core": "^7.1.0",
    "@babel/plugin-external-helpers": "^7.0.0",
    "babel-core": "^7.0.0-0",
    "babel-preset-env": "^1.7.0",
    "metro-react-native-babel-preset": "^0.45.0"
    ...
 }

.babelrc

{
  "presets": ["module:metro-react-native-babel-preset"]
}

In the end I get some error logs from some different devices saying :

"undefined is not a function (evaluating 't.map(function(t){return u(t)})')" indicating "queryListToInfoList" function. But generally it works.

queryList is always an array. (response.data)

What might be causing the problem here?

Thanks in advance

Update:

Digging a bit more, I realize all those error logs have something in common. This crash happens after an Android intent e.g: POWER_DISCONNECTED, RINGER_MODE_CHANGED, CONFIGURATION_CHANGED.

2 Answers

this might sound silly, did you tried importing the queryListToInfoList as import {queryListToInfoList} from './path_to service' or import queryListToInfoList from './path_to service'. i have seen these error happen usually when imported in a wrong way

After a while, I found the problem. It happens because sometimes apisauce/axios cannot parse response.data correctly. So instead of object it passes string and the rest throws error when referencing string.map()

Here is the issue axios parse error

As a workaround, I added type checks before setting response.data, so it is now like following after api calls:

if(response.ok && typeof response.data === 'object'){
  dispatch(setData(response.data || []));
}

Beware this should be okay only if expected data is actually object type.

Related