This is the third part in a series on Redux, a state Management Framework used with single page application frameworks such as React and Angular. This article series looks at using Redux without another framework. Please read part 1, and Part 2 before reading this.

I write about Redux and Angular in the bonus book to the Angular 6 series.

This article will expand on the previous "hello world" sample to teach you how to say Goodbye.

Add a new state to the Reducer

With every hello comes a goodbye. We are going to create a button that will say goodbye to the user, and then clear out the helloUser value from the store. The purpose of this sample is to add more objects in the store.

First, let's start with the UI:

view plain print about
1<button id="goodbyebtn">GoodBye</button><br/><br/>
2GoodBye <span id="goodbyeValue"></span>

I added a Goodbye Button, and a span for the goodbyeValue. Back to the JavaScript, handle a click on the goodbyebtn:

view plain print about
2 .addEventListener('click', function (e) {
3 store.dispatch({ type: 'NAME_LEFT',
4 value : store.getState().helloUser})

This dispatches an action. The type is NAME_LEFT. The value is the current helloUser.

Let's go back to our reducer function and add some code to handle this new action:

view plain print about
1case 'NAME_LEFT':
2 newState.goodbyeUser = action.value;
3 newState.helloUser = '';
4 break;

It is just another case statement in the switch. We set a new value on the state to goodbyeUser, and set the helloUser value to an empty string. When we set the default, near the beginning of the reducer() method, be sure to initialize the goodbyeUser state property:

Now we need to create a function to render the code:

view plain print about
1function renderGoodbye() {
2 document.getElementById('goodbyeValue').innerHTML =
3 store.getState().goodbyeUser.toString()

This just uses getElementByID() to get the span for the goodbyeValue. It sets the innerHTML to the stores goodbyeUser property. Make sure you subscribe: store.subscribe(renderGoodbye)

The code should be runnable now:

Enter your name and you'll "Hello Jeffry", just as with our original sample. Then click the GoodBye button, and you'll see the name populate after Goodbye and the name after Hello blank out. I did not add code to blank out the user input, but you should be able to do that easily if needed.

Play with a live sample here.