How to pass a callback in redux-toolkit and return a value

Viewed 83

i have a situation where i need to dispatch and action and call an APi,once the Api returns result i want to show modal or ridirect,if API result length is 1,i need to ridirect user to another otherwise,i need to show modal on the same screen, Now i want to implemnt this using callback ,or if you have another better approach please suggest.

//dispatching Action

const getStores = (store) => {
    const obj = {
      storeId: store._id,
      areaId:store.areadId
    };
    dispatch(StoreAction.getStores(obj));
  };

//slice code

getAreaStores: (state) => {
      state.loading = true;
      state.error = null;
      state.stores = [];
    },
    getAreaStoresSuccess: (state, action) => {
      state.loading = false;
      state.stores = action.payload;
      state.error = null;
    },
    getAreaStoresFailure: (state, action) => {
      state.loading = false;
      state.error = action.payload;
    },

//saga code

function* getStores({ payload }) {
  try {
    const response = yield call(API.getStores, payload);

    if (response.success == "1") {
      yield put(StoreAction.getAreaStoresSuccess(response.data));
      }
    } else {
      yield put(StoreAction.getAreaStoresFailure(response.error));
    }
  } catch (error) {
    yield put(StoreAction.getAreaStoresFailure(error));
  }
}
1 Answers

We don't pass a callback in redux actions/sagas. Update the value in store inside your saga once you get response from the API and your components will listen to the store, as soon as the data is in the store your component will automatically be notified, there you will check the length of the data to show the modal or redirect.

Related