In the last lecture, we learned how to also pass data with the action, how to retrieve it.
Now with that, we learn some of the very core concepts of using redux.
Now if we have a look at our reducer here, there is something you will probably notice, it already has
a lot of code replication, a lot of if statements.
Now there's nothing wrong with using if statements, if you like that, use that approach
but we could also use a different type of statement, expression in javascript,
the switch statement. We could switch the action type and then define multiple cases like the increment
case,
then we have a colon
so normal javascript syntax and then here, we could return this updated state for the increment case
and now we can get rid of that if statement.
And now we can of course add more cases here,
so one case for decrement and I don't need to add a break statement because return automatically
exits out of this function we never reached this line then, only of course if we get into this case in the
first place.
So for decrement, we would also return a state here,
we would return this state. And now we can repeat this of course for all the cases, so I'll quickly add a case
for adding and a case for subtracting
and of course these identifiers still have to match the identifiers you use when dispatching actions.
So the identifier you said here on the type in the counter container and now I'll pull out the code from
these if statements and
add them, add the code to their respective cases here. Reformat the code and get rid of these if statements
and now our reducer is a bit leaner and a bit easier to read because it's very clear that we're looking
at the action type and then we're just handling different cases.
And if we don't make it into any of these cases, we always have the default return statement here at
the end which returns our either initial state
or if this was already set, the current state. This is especially important since we have to keep in
mind that if we were to dispatch an action which has a type which is not covered here, we would still run
through that reducer because when ever you dispatch something, it goes through that single reducer you have
in your application.
Therefore if that reducer doesn't handle that action type you dispatched,
you have to return the current state to not break your application.
So with that, let's save all these files and you will see that if you go back, it still works as before
but now with these central reducers still but there, with the switch statement.