Check out our Angular Book Series.

Learning Redux - Define an Initial State - Part 4

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

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

I want to expand on our previous sample to define an initial state. Technically we already do that inside the reducer, like this:


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

But, this can be simplified with some code tweaks. First, define the initial state:


var initialState = {
helloUser : '',
goodbyeUser : ''
}

Now change the reducer method signature:


function reducer(state = initialState, action) {

We're using syntax shorthand to define the default argument if state is undefined. Try to run things again, and the app should work.

In a real-world app, I'd probably create the state as its own class, and pass a new instance of the state into the method as the default argument. Such details are left out in this proof of principle sample.

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.