jack volten
jack volten

Reputation: 273

How can I avoid requesting redox-saga action several times?

If an error occurs when executing the getPost function, I want to run REFRESH_REQUEST through catch (err), and when REFRESH_SUCCESS is complete, I want to run GETPOST_REQUEST again.

However, with my code, GETPOST_REQUEST and REFRESH_REQUEST run multiple times and GETPOST_GETPOST_SUCCESS succeeds first.

However, I want the both REQUEST to be executed only once, and the REFRESH_SUCCESS succeeds first and then the second I want GETPOST_SUCCESS to succeed.

this is my code how can i fix my code?

    function getPostAPI(data) {
      return axiosInstace.post('/kakao/getpost', data);
    }

    function* getPost(action) {
      try {
        const result = yield call(getPostAPI, action.data);
        yield put({
          type: GETPOST_SUCCESS,
          data: result.data,
        });
      } catch (err) {
        yield put({
          type: REFRESH_REQUEST,
        });
        yield put({
          type: GETPOST_REQUEST,
          data: action.data,
        });
      }
    }

    function refreshAPI() {
      return axiosInstace.post('/kakao/refresh');
    }

    function* refresh() {
      try {
        const result = yield call(refreshAPI);
        AsyncStorage.setItem('accesstoken', `${result.data.accessToken}`, () => {});
        yield put({
          type: REFRESH_SUCCESS,
          data: result.data,
        });
      } catch (err) {
        yield put({
          type: REFRESH_FAILURE,
          error: err.response.data,
        });
      }
    }

Upvotes: 0

Views: 33

Answers (1)

Nageshwar Reddy Pandem
Nageshwar Reddy Pandem

Reputation: 1047

maintain reducer with status of api calling like below

initially, store contains status equal to initial

so when one action called, make status to loading and dont call action if its already loading state...

Note: I explained this code in redux-thunk way, but try to understand the logic, it will be same wherever.

I hope you understand

type status = 'initial' | 'loading' | 'success' | 'error';

const initialState = {
  status: 'initial'
}

in getPost error function, you can check for the status of api...

const getPost = () => {
  return (dispatch, getState) => {
    const state = getState();
    GETPOST_REQUEST;
    try {
      GETPOST_SUCCESS;
    } catch(error) {
      GETPOST_ERROR;
      
      if (state.status !== 'loading') {
        dispatch(refresh())
      }
    }
  }
}

const refresh = () => {
  return (dispatch, getState) => {
    const state = getState();
    REFRESH_REQUEST;
    try {
      REFRESH_SUCCESS;
      dispatch(getPost())
    } catch(error) {
      REFRESH_ERROR;
    }
  }
}

Upvotes: 1

Related Questions