Creating Action in Redux
In this lesson, we're going create actions
Creating actions in Redux#
So we now see the data on screen, but it's not just about displaying the data; we should also be able to update it. We can do this with the help of the redux actions. Whenever the action is ran, it re-renders the application which shows us the updated state. Let's start working on it right away.
In traditional redux, there are actions as well as action types which are nothing but the name of the action being called, so let's create one for our experiment and let's call it UPDATE_VISIT. Usually, what happens is that we have a separate file for all the action types, then we have a separate file for the actions and a separate one for the reducers. We then call the action type to check what kind of action we want to use to update the state. It generally happens with the help of switch statement, which we can use inside loginReducer.
We will use switch on action.type and the only case we have is the UPDATE_VISIT, which will add one to our current state. The most important rule we have in Redux is to never mutate the state, so we can't use it directly. We will use spread operator which will give us the copy of the mutated state. For the default case, we can simply return the state. We can remove this state now.
When we use the action, we usually call it dispatch in Redux terminology. So what we can do is go to Login page and use the dispatch from useDispatch to update the count. The counter that we created is what we're going to use to tell our reducer what to do with the state. We just have one action type right now, but suppose we had more than one, how would our reducer know which action to perform? Let's use dispatch when the page renders, so we can use it inside the useEffect hook.
We will use dispatch and pass an object with type and as value, we will provide the action type which is UPDATE VISIT. What will happen is that we would use the dispatch with type UPDATE VISIT. It will call our reducer and see what to do with it. it will also match the action type and will return a new state. We can also make a button with onClick event which will dispatch the same action. Let's go to the browser now, and as soon as we reach the page, we see visits are 2, because our initial state is 1. Also, if we click on the button, we see that the count is increasing. This shows how the actions work in redux.
This page is a preview of The newline Guide to Fullstack ASP.NET Core and React