prajeesh
prajeesh

Reputation: 2382

Calling a function from inside the generator function

I need to call the function displayError from inside a generator function. The code is as follows.

function* createPatient(action) {
  try {
    yield call(createPatientApi, action.payload);
    yield put({ type: types.PATIENT_CREATE_SUCCESS });
    yield put(constants.successMsg(patientCreateSuccess));
  } catch (error) {
    // dispatch a failure action to the store with the error
    displayError(error)
  }
}

function displayError(error) {
  if (error.response && !(error.response.data.success)) {
    let resp = error.response.data;
    yield put({ type: types.PATIENT_CREATE_FAILURE, resp });
  } else {
    yield put(constants.DEFAULT_ERROR_MSG);
  }
}

But i am getting the following error.

Parsing error: yield is a reserved word in strict mode

I tried modifying the function as

function* displayError(error) {
 ..
}

and invoking it as yield call(displayError(error))

but it does not seem to work. Any idea on how to fix this?

Upvotes: 1

Views: 628

Answers (1)

nromaniv
nromaniv

Reputation: 765

You need to make displayError a generator and feed its argument as the second argument to call effect. Like so:

yield call(displayError, error);

The reason is that displayError(error) gets evaluated at the call site and this expression returns an iterator object, and then saga runtime tries to call it as a function, which does not work.

Upvotes: 2

Related Questions