0
votes

I tried to make an API call, but the yield put fired before the yield call finished the execution. Here is my code:

Api.js

function callApi(endpoint, token = null) {
  const fullUrl =
    endpoint.indexOf(API_ROOT) === -1 ? API_ROOT + endpoint : endpoint;

  return axios
    .get(fullUrl, { headers: { Authorization: token } })
    .then(resp => {
      return Object.assign([], resp.data);
    })
    .catch(error => ({ error: error.message || "Something bad happened" }));
}

export const checkOpenRegister = (branchId, userId, token) => {
  console.log("in check open");
  callApi(
    `Branches/${branchId}/registers?filter[where][status]=1&filter[where][userId]=${userId}`,
    token
  );
};

and in my saga index.js

function* doCheckAuthInfo() {
  try {
    const user = yield select(getUser);

    if (user.token) {
      yield put({
        type: CHECK_AUTH_INFO_SUCCEED,
        payload: { token: user.token }
      });
      yield put({ type: CHECK_OPEN_REGISTER_REQUESTED });
    } else {
      //redirect to login
      yield put(NavigationActions.navigate({ routeName: "Login" }));
    }
  } catch (error) {
    yield put({ type: CHECK_AUTH_INFO_FAILED, error });
  }
}

function* doCheckOpenRegister() {
  try {
    const user = yield select(getUser);

    const response = yield call(
      checkOpenRegister,
      user.branchId,
      user.userId,
      user.token
    );
    yield put({ type: CHECK_OPEN_REGISTER_SUCCEED, payload: response });
  } catch (error) {
    yield put({ type: CHECK_OPEN_REGISTER_FAILED, error: error.message });
  }
}

function* watchCheckAuthInfo() {
  yield takeLatest(CHECK_AUTH_INFO_REQUESTED, doCheckAuthInfo);
}

function* watchCheckOpenRegister() {
  yield takeLatest(CHECK_OPEN_REGISTER_REQUESTED, doCheckOpenRegister);
}

// use them in parallel
export default function* rootSaga() {
  yield all([
    fork(watchCheckAuthInfo),
    fork(watchCheckOpenRegister)
  ]);
}

In my saga, on function doCheckOpenRegister, yield PUT fired with no payload but I can find the payload in my network debugger.

I need the payload to trigger action to redirect. In this case, when there is a value in response I need to redirect to main page.

1

1 Answers

2
votes

you forgot return Promise from function checkOpenRegister

export const checkOpenRegister = (branchId, userId, token) => {
  console.log("in check open");
  return callApi(
    `Branches/${branchId}/registers?filter[where][status]=1&filter[where][userId]=${userId}`,
    token
  );
};