1

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?

buenon
  • 145
  • 8

2 Answers2

1

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);
      }
  }
}),
Kavinda Jayakody
  • 705
  • 1
  • 13
  • 25
  • The problem is that when I call dispatch.session.logout(); without sending any argument I get the typescript error: TS2554: Expected 1 arguments, but got 0. types.d.ts(125, 7): An argument for 'payload' was not provided. – buenon May 31 '22 at 05:31
  • Sorry, yes it is. Sorry I tried it without the rootState. That way, it doesn't give any errors. Will remove my answer. We probably need to add this as an issue to rematch's github issues – Kavinda Jayakody Jun 01 '22 at 12:12
  • Hey @buenon. I've edited the answer. Try it now. Simply, pass the first argument as _: void. This is working for me – Kavinda Jayakody Jun 29 '22 at 08:35
0

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);
}