RematchJS - how can I access the state in a model's effect without sending a payload to dispatch

726 Views Asked by At

I'm using RematchJS and I'd like to access the state in a model effect without sending a payload to the effect.
The model looks something like this:

export const session = createModel<RootModel>()({
  state: {
    ...
  } as SessionModel,
  reducers: {
    setAuthenticated(state, payload) {
      return {
        ...state,
        isAuthenticated: payload,
      };
    }
  },
  effects: (dispatch) => ({
    async logout(payload, rootState) {
      const sessionId = rootState.session.sessionId;

      if (sessionId) {
        await ApiClient.logout(sessionId);
        dispatch.session.setAuthenticated(false);
      }
    }
  }),
});

The problem is that since the payload comes first in an effect, I must send some payload when I dispatch the effect otherwise typescript will complain:

dispatch.session.logout(somePayload);

I work around that by calling dispatch.session.logout(null); but it feels incorrect.
Is there a nicer solution?

2

There are 2 best solutions below

3
On BEST ANSWER

Pass the first parameter as _: void. Tried and made it work

effects: (dispatch) => ({
  async logout(_:void, rootState) {
      const sessionId = rootState.session.sessionId;

      if (sessionId) {
        await ApiClient.logout(sessionId);
        dispatch.session.setAuthenticated(false);
      }
  }
}),
0
On

You can use the getState function that is available in the dispatch object

// use getState() to access the state in the effect
const sessionId = dispatch.getState().session.sessionId;

if (sessionId) {
  await ApiClient.logout(sessionId);
  dispatch.session.setAuthenticated(false);
}