Kontext
The reducer function and state initialize
Then since we have already created our store, and our actions, it is time to create the state, the balance in our example.
For now this will hold only a single value, but it can possibly hold as many as we want. So after our actions in our script we will initialize our state. These are going to be the initial values of state. We want to set our balance cashier of the family to 0$. So it is completely empty at the beginning. And we do this at line 12. You can name the variable as you like.
But then, later we create our reducer function. This function, can accept many different actions and it is responsible to execute them accordingly. As you can see above, reducer (it has to be named like that, because this is how we passed it as an argument inside the createStore function), accepts two mandatory arguments. The one is the state, because the reducer's job is to perform operations on state, and the other is the action, because the reducer must know somehow what has to be done on state (deposit or withdraw?).
So as a first argument, we pass a default value, which is the already initialized state 2 lines above. Then we implement a switch-case pattern, to execute different code depending of the type property of the triggered action.
Remember! The action object is passed as a second parameter, and we check the type property to execute accordingly. In both cases we use the amount property either to deduct or to add to the current state.
The reducer at ALL CASES must return the updated state at the end of it.
Attention: Since this is ready, place the line of code where you create the actual store, AFTER the definition of the reducer function. That's because the reducer it is used inside the createStore and it has to be defined before thus.
In the case of deduction (or withdraw) we have also implemented a small bonus task, to prevent someone to withdraw more money than they exist.
Attention again: Don't forget to add a default case, where the state is just returned. This will be executed when the action's type was not recognized.