Search code examples
javascriptreactjsredux-thunkdispatchdispatch-async

Unhandled Rejection (TypeError): dispatch is not a function getting this error in action creator


I am getting this error while dispatch is called.

Unhandled Rejection (TypeError): dispatch is not a function

here is my action creator code where I am getting above error.

export function getStatus(requestId) {
  return async dispatch => {
    let url = GET_UPLOADED_STATUS_URL + requestId;
    let response = await get(url);
    const timeout = setTimeout(getStatus(requestId), 2000);
    if (response.status === 200) {
      let total = response.payload.count;
      let totalCompleted = response.payload.uploadCompleted
      dispatch({
        type: UPDATE_PROGRESS_BAR_STATUS,
        total: total,
        completed: totalCompleted
      })
      if (!response.payload == "") {
        toastr.info(`Total processed ${totalCompleted}`);
      }
      if (response.payload === "") {
        dispatch({
          type: SHOW_PROGRESS_BAR,
          data: false
        })
        clearTimeout(timeout);
      }
    } else {
      clearTimeout(timeout);
      dispatch({
        type: SHOW_PROGRESS_BAR,
        data: false
      });
    }
  }
}

As you can see I am calling this action in every two second.Its work fine for first time execution but while executing second time its through above error while dispatching UPDATE_PROGRESS_BAR_STATUS. and in console getting this error.

Uncaught (in promise) TypeError: dispatch is not a function
    at _callee3$ (index.js:100)

can someone please guide me what I am doing wrong here or why I am getting this error.any help will be appreciated thanks in advance.

here is my updated code where how I am calling getStatus() action.

export function uploadFileFolder(arrayofFile, jdId) {
  return async dispatch => {
    dispatch({
      type: REQUEST_INITIATED
    });
    let url = UPLOAD_FILE_FOLDER_URL + jdId;
    let response = await post(url, arrayofFile);
    if (response.status === 200) {
      dispatch({
        type: REQUEST_SUCCESSED
      });
      history.push({
        pathname: "/file-list/" + jdId
      });
      toastr.success(response.payload.message);
      dispatch({
        type: SHOW_PROGRESS_BAR,
        data: true
      });
      let requestId = response.payload.requestId;
      dispatch(getStatus(requestId));
    } else {
      dispatch({
        type: REQUEST_SUCCESSED
      });
    }
  }
}

and uploadFileFolder() action I am calling this by click on button in my component.


Solution

  • You getting this error because when you calling getStatus() action after every 2 seconds is not getting dispatch. As you said its working fine for first-time execution but while calling the 2nd time it's through an error because for the second time it's not getting dispatch. So you need to update your code like given below.

    const timeout = setTimeout(dispatch(getStatus(requestId), 2000));