'How do I correctly implement Redux Saga action dispatches?

I'm currently playing around with redux saga and I'm having troubles implementing it correctly. Let's say I have a reducer which keeps track of how many times the app is launched:

const startedAppState = createSlice({
  initialState,
  name: 'started-app',
  reducers: {
   incrementStartedAppCounter: (state: IUserAuthenticationState) => ({
      ...state,
      startedAppCounter: state.startedAppCounter + 1,
    }),
  },
});

Then I export the incrementStartedAppCounter action like this:

export const {
  incrementStartedAppCounter,
} = startedAppState.actions;

In my saga generator functions I call it the following way:

function* appStartOrSomething() {
  yield put(incrementStartedAppCounter());
}

Now this works, and the startedAppCounter is increased every time I launch the app. The issue is, that now my IDE complains (obviously) that incrementStartedAppCounter() in the sage expects a parameter (the state). If I dispatch the action like this yield put(incrementStartedAppCounter) the counter isn't increased - which I expected. How would I call this correctly? How would I implement it if I want to add another parameter, e.g. yield put(setStartedAppCounter(5))?

I feel like I went into the wrong direction there somewhere, can anybody help me out? Thanks a lot!



Solution 1:[1]

yield put(incrementStartedAppCounter()); is the correct syntax. Action creators (like your increment function) are functions so that they can easily accept arguments like your second example. An action creator with no arguments must still be invoked to be dispatched (or put, in saga language).

createSlice from Redux Toolkit uses createAction and createReducer under the hood. You can read more about their action creators in their docs: https://redux-toolkit.js.org/api/createAction

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Abe