I am getting Cannot read property 'then' of undefined while calling the api in react

限于喜欢 提交于 2020-01-06 05:43:10

问题


I am getting TypeError: Cannot read property 'then' of undefined when calling the api in react.js and redux.

my component did mount function is -

componentDidMount() {
    window.scrollTo(0, 0);
    var requestedId = this.props.match.params.id;
    this.props.fetchCategoryJoblist(requestedId).then(() => {
      this.setState({ loading: false });
    });
  }

I am getting can not read property of then at this line this.props.fetchCategoryJoblist(requestedId).then(())

My componentDidMount function -

componentDidMount() {
    window.scrollTo(0, 0);
    var requestedId = this.props.match.params.id;
    this.props.fetchCategoryJoblist(requestedId).then(() => {
      this.setState({ loading: false });
    });
  }

My action.js file -

// code to get job listing based on category
export function setCategoryJoblist(categoryjoblist) {
  return {
    type: SET_CATEGORY_JOBLIST,
    categoryjoblist
  };
}

export function fetchCategoryJoblist(requestedId) {
  var apiUrl = `http://18.207.190.61:4000/getJobByCategory/${requestedId}`;
  return dispatch => {
    fetch(apiUrl)
      .then(res => res.json())
      .then(data => dispatch(setCategoryJoblist(data.Jobs)));
  };
}

So how can I use then method in componentDidMount Method ?


回答1:


Your fetchCategoryJobList

export function fetchCategoryJoblist(requestedId) {
  var apiUrl = `http://18.207.190.61:4000/getJobByCategory/${requestedId}`;
  return dispatch => {
    // see here
    fetch(apiUrl)
      .then(res => res.json())
      .then(data => dispatch(setCategoryJoblist(data.Jobs)));
  };
}

Maybe the problem is in here

export function fetchCategoryJoblist(requestedId) {
  var apiUrl = `http://18.207.190.61:4000/getJobByCategory/${requestedId}`;
  return dispatch => {
    // you don't have return here, so your call to API is won't return a promise call CMIIW
    return fetch(apiUrl)
      .then(res => res.json())
      .then(data => dispatch(setCategoryJoblist(data.Jobs)));
  };
}


来源:https://stackoverflow.com/questions/57743929/i-am-getting-cannot-read-property-then-of-undefined-while-calling-the-api-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!