Farukh Khan
Farukh Khan

Reputation: 315

Reactjs: Uncaught (in promise) TypeError: Cannot read property 'data' of undefined

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,
            };

Upvotes: 1

Views: 1773

Answers (4)

Farukh Khan
Farukh Khan

Reputation: 315

Well, After thorough deep understanding of code, I came to the conclusion that we were using interceptors to pass throught the response.

the interceptor looks like this before

 axios.interceptors.response.use(
    response => {
      if (response.status !== 200) {
        const error =
          (response.data && response.data.message) || response.statusText;
        cogoToastHelper.error(error);
        console.log("I am here in Interceptor");
        return Promise.reject(error);
      }
      console.log("I am here in Interceptor before cogoToast");
      cogoToastHelper.info(response.data.message);
      //return response.data.data;
      console.log("HERE RESPONSE" + response.data.data);
        return response.data.data;

So I changed this into the code below

 axios.interceptors.response.use(
    response => {
      if (response.status !== 200) {
        const error =
          (response.data && response.data.message) || response.statusText;
        cogoToastHelper.error(error);
        console.log("I am here in Interceptor");
        return Promise.reject(error);
      }
      console.log("I am here in Interceptor before cogoToast");
      cogoToastHelper.info(response.data.message);
      //return response.data.data;
      console.log("HERE RESPONSE" + response.data.data);
      if (response.data.data !== undefined) {
        console.log("I got response.data.data");
        return response.data.data;
      } else {
        console.log("I got response.data");
        return response.data;
      }

and now it works.

Upvotes: 1

Pushprajsinh Chudasama
Pushprajsinh Chudasama

Reputation: 7949

You need to make your response as a parameter in .then method see below

   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);
      }
    });

Upvotes: 0

Ashif Zafar
Ashif Zafar

Reputation: 637

You can try something like

const token = userService.getToken();

  const api = `http://localhost:54729/api/Search?searchString=${text}`;
  const resData = async()=> axios.get(api, { headers: { Authorization: `Bearer ${token}`

try{
console.log(resData.data,"Response from api")
dispatch({type: FETCH_PRODUCTS,payload: resData.data});
}
catch(e){
 console.log("error" + err);
}


Upvotes: 0

Luïs
Luïs

Reputation: 2843

Your res object has no data object in it. Your res is the array which your API returns. So just executing console.log(res) instead of console.log(res.data) should do the trick.

Upvotes: 1

Related Questions