Check out our Angular Book Series.

Learning Redux - Saying Goodbye to Hello World - Part 3

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:


<button id="goodbyebtn">GoodBye</button><br/><br/>
GoodBye <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:


document.getElementById('goodbyebtn')
.addEventListener('click', function (e) {
store.dispatch({ type: 'NAME_LEFT',
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:


case 'NAME_LEFT':
newState.goodbyeUser = action.value;
newState.helloUser = '';
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:


if (typeof state === 'undefined') {
newState = {
helloUser : '',
goodbyeUser : ''
}
}

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


function renderGoodbye() {
document.getElementById('goodbyeValue').innerHTML =
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.

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
All Content Copyright 2005, 2006, 2007, 2008, 2009 Jeffry Houser. May not be reused without permission
BlogCFC was created by Raymond Camden. This blog is running version 5.9.2.002.