I am pretty new to reactjs, I am trying to call an api data to get the response through axios. But getting the same error again and again.
Error Uncaught (in promise) TypeError: Cannot read property 'data' of undefined.
There are so many similar questions but I couldn't find any answer that could help me. The code I am using is given below.
Code
const token = userService.getToken();
const api = `http://localhost:54729/api/Search?searchString=${text}`;
axios
.get(api, { headers: { Authorization: `Bearer ${token}` } })
.then(res => {
console.log("hello" + res);
try {
dispatch({
type: FETCH_PRODUCTS,
payload: res.data// Dummy data
});
} catch (err) {
console.log("error" + err);
console.log(res.data);
}
});
Edit
The response from api is
[
{
"id": 0,
"title": "example-, example- und example(CC 11): example– example Berlin",
"description": null,
"owner": null,
"link": "/search/herz?url=https://www.example.de/example/example/example/",
"url": "https://www.example.de/example/charitecentren/example/",
"type": "External",
"rank": 0
},
{
"id": 0,
"title": "example Klinik mit exampleKardiologie (example) - Charité – example Berlin",
"description": null,
"owner": null,
"link": "/search/herz?url=https://example-cvk.example.de/",
"url": "https://example-example.example.de/",
"type": "External",
"rank": 0
},
{
"id": 0,
"title": "Deutsche Zentren example example: example– Universitätsmedizin example",
"description": null,
"owner": null,
"link": "/search/herz?url=https://www.example.de/forschung/example/example/",
"url": "https://www.example.de/example/example/deutsche_zentren_fuer_gesundheitsforschung/",
"type": "External",
"rank": 0
},
]
when I console.log(res.data)
it says undefined
.
Also, nobody has asked me yet till now what dispatch: FETCH_PRODUCTS
is doing really. You can see it below. May be it will help, what I am trying to do.
case FETCH_PRODUCTS:
console.log(action)
return {
...state,
products: action.payload,
loading: false,
totalRecords: action.payload.length,
};
res
what does it show? Probablyres
doesn't havedata
property inside. – octobusconsole.log(res)
also undefined? – octobus