Search code examples
reactjsreact-reduxredux-sagaredux-reducers

Get the state variable after dispatch is finished in react redux and saga?


Hello I am fairly new to React, Redux and Saga. So I have a scenario where I have a .jsx file which is the view file then an action file used for dispatch and I am also using saga which updates the data in the reducers. Following are the file structurs:

  1. Action file:
export const getAction = (requestor) => ({
  type: GET_ACTION,
  data: {
    requestor,
  },
});
  1. Reducer file
export const Reducer = (currentState = {}, action) => {
  const newState = { ...currentState };

  switch (action.type) {
    case GET_ACTION:
      newState.data = action.data;
      return newState;
  }  
};
  1. Saga file
function* getData(action) {
  const { requestor } = action.data;
  try {
    const data = yield call(callService);
    if(success) {
      yield put( {type: GET_ACTION, data} );
    }
  } catch (e)
  {
  }
}

function* getDataSaga() {
  yield takeLatest(GET_ACTION, getData);
}

export {
  getData,
};

export default [
  getDataSaga,
];
  1. jsx file
const [dummy, setDummy] = useState([]);
const data = useSelector(state => state.data, shallowEqual) || {};

There is a function in which dispatch function is called.

dispatch(getAction(requestor));

Now I need to access the updated state of data after dispatch has finished updating the data because after the data is updated I have to setDummy to set the dummy variable mentioned. Any way which I can be approaching to achieve that. I have tried to use dispatch.then but on UI it is saying .then is not a function for dispatch.


Solution

  • after the data is updated I have to setDummy

    useEffect lets you do something upon a given prop changing

    const [dummy, setDummy] = useState([]);
    const data = useSelector(state => state.data, shallowEqual) || {};
    
    // setDummy when `data` changes
    useEffect(() => {
      setDummy(data);
    }, [data])