Final Implementation
Learn how to use Redux in your application.
To complete our example, let’s switch to the real Redux
library and see how similar the solution remains.
First, add the Redux library, for now using unpkg:
<script src="https://unpkg.com/redux/dist/redux.js" />
We then change our previous state definition to be a constant that only defines the initial value of the state:
const initialState = {
counter: 3
};
Now we can use it to create a Redux store
:
const store = Redux.createStore(reducer, initialState);
As you can see, we are using our reducer
from before. The switch
statement is the only change that needs to be made to the reducer. Instead of using just the action:
switch (action)
,
we include the mandatory type
property, which indicates the type of action being performed:
switch (action.type)
The Redux store
will also give us all the features we implemented ourselves before, like subscribe()
and dispatch()
. Thus, we can safely delete these methods.
To subscribe to store changes, we simply call the subscribe()
method of the store:
store.subscribe(updateView);
subscribe()
does not pass the state to the callback, so we need to access it via store.getState()
:
//Updating view by reading the state from the store
// Function to update view (this might be React or Angular in a real app)
function updateView() {
document.querySelector('#counter').innerText = store.getState().counter;
}
store.subscribe(updateView);
The last change is in the dispatch()
method. As mentioned previously, our actions now need to have the type
property. Thus, instead of sending the string 'INC'
as the action, we now need to send { type: 'INC' }
.
Here is what the complete code will look like:
Get hands-on with 1300+ tech skills courses.