An Nguyen
An Nguyen

Reputation: 800

redux-saga doesn't work at the first time

I have a redux-saga as below:

export function* loadApplianceSaga() {
  try {
    let {request, success, error} = yield take(ActionTypes.APPLIANCE.LOAD);
    request.url = yield select(getResourceLink, request.resource);
    const response = yield call(makeRequest, request);
    if (!response.error) {
      yield put({type: success, payload: response.body});
    } else {
      yield put({type: error, payload: response});
    }
  } catch (e) {
    yield put({type: ActionTypes.REQUEST.CALL_ERROR, error: e});
  }
}

export function* watchLoadAppliance() {
  while (true) {
    yield* takeEvery(ActionTypes.APPLIANCE.LOAD, loadApplianceSaga);
  }
}

and root saga:

export default function* rootSaga() {
  yield [
    fork(watchLoadAppliance)
  ]
}

I'm facing a problem that loadApplianceSaga doesn't work at the first time. I logged and saw that in the first time it only dispatched ActionTypes.APPLIANCE.LOAD action then no action is dispatched. But in the second time, I can see success action or failed action which are dispatched.

Could anyone tell me what was wrong? Thanks in advance!

Updated action:

export const loadAppliances = () => {
  return {
    type: ActionTypes.APPLIANCE.LOAD,
    request: {
      resource: Resources.Appliances,
      param: {
        page: 0,
        size: 5,
        sort: 'name,desc'
      },
      header: {
        Accept: 'application/json'
      }
    },
    success: ActionTypes.APPLIANCE.LOAD_SUCCESS,
    error: ActionTypes.APPLIANCE.LOAD_ERROR
  }
};

Upvotes: 3

Views: 2241

Answers (1)

Kokovin Vladislav
Kokovin Vladislav

Reputation: 10391

you have used take two times. try

export function* loadApplianceSaga(action) {
  try {
    let {request, success, error} = action;
    request.url = yield select(getResourceLink, request.resource);
    const response = yield call(makeRequest, request);
    if (!response.error) {
      yield put({type: success, payload: response.body});
    } else {
      yield put({type: error, payload: response});
    }
  } catch (e) {
    yield put({type: ActionTypes.REQUEST.CALL_ERROR, error: e});
  }
}

export function* watchLoadAppliance() {
  while (true) {
    yield* takeEvery(ActionTypes.APPLIANCE.LOAD, loadApplianceSaga);
  }
}

Upvotes: 4

Related Questions