Redux
Redux
Think of Redux actions as messengers that deliver information about events happening
in your app to the Redux store. The store then conducts the business of updating state
based on the action that occurred.
Recall that action creators return an object with a type property that specifies the type of
action that has occurred. Then the method dispatches an action object to the Redux store.
Based on the previous challenge's example, the following lines are equivalent, and both
dispatch the action of type LOGIN:
store.dispatch(actionCreator());
store.dispatch({ type: 'LOGIN' });
The code editor has the previous example as well as the start of a reducer function for
you. Fill in the body of the reducer function so that if it receives an action of
type 'LOGIN' it returns a state object with login set to true. Otherwise, it returns the
current state. Note that the current state and the dispatched action are passed to the
reducer, so you can access the action's type directly with action.type.
const defaultState = {
login: false
};
The code editor has a store, actions, and action creators set up for you. Fill in
the reducer function to handle multiple authentication actions. Use a
JavaScript switch statement in the reducer to respond to different action events. This is a
standard pattern in writing Redux reducers. The switch statement should switch
over action.type and return the appropriate authentication state.
Note: At this point, don't worry about state immutability, since it is small and simple in this
example. For each action, you can return a new object — for example, {authenticated:
true}. Also, don't forget to write a default case in your switch statement that returns the
current state. This is important because once your app has multiple reducers, they are all
run any time an action dispatch is made, even when the action isn't related to that reducer.
In such a case, you want to make sure that you return the current state.
const defaultState = {
authenticated: false
};
switch (action.type) {
case "LOGIN":
return {
authenticated: true
};
case "LOGOUT":
return {
authenticated: false
};
default:
return defaultState;
}
// Change code above this line
};
const store = Redux.createStore(authReducer);
Write a callback function that increments the global variable count every time the store receives
an action, and pass this function in to the store.subscribe() method. You'll see
that store.dispatch() is called three times in a row, each time directly passing in an action object.
Watch the console output between the action dispatches to see the updates take place.
store.dispatch({type: ADD});
console.log(count);
store.dispatch({type: ADD});
console.log(count);
store.dispatch({type: ADD});
console.log(count);
Typically, it is a good practice to create a reducer for each piece of application state when
they are distinct or unique in some way. For example, in a note-taking app with user
authentication, one reducer could handle authentication while another handles the text and
notes that the user is submitting. For such an application, we might write
the combineReducers() method like this:
Now, the key notes will contain all of the state associated with our notes and handled by
our notesReducer. This is how multiple reducers can be composed to manage more complex
application state. In this example, the state held in the Redux store would then be a single
object containing auth and notes properties.
There are counterReducer() and authReducer() functions provided in the code editor, along
with a Redux store. Finish writing the rootReducer() function using
the Redux.combineReducers() method. Assign counterReducer to a key
called count and authReducer to a key called auth.
There's a basic notesReducer() and an addNoteText() action creator defined in the code
editor. Finish the body of the addNoteText() function so that it returns an action object.
The object should include a type property with a value of ADD_NOTE, and also
a text property set to the note data that's passed into the action creator. When you call
the action creator, you'll pass in specific note information that you can access for the
object.
Next, finish writing the switch statement in the notesReducer(). You need to add a case
that handles the addNoteText() actions. This case should be triggered whenever there is
an action of type ADD_NOTE and it should return the text property on the
incoming action as the new state.
The action is dispatched at the bottom of the code. Once you're finished, run the code
and watch the console. That's all it takes to send action-specific data to the store and
use it when you update store state.
console.log(store.getState());
store.dispatch(addNoteText('Hello!'));
console.log(store.getState());
In this example, an asynchronous request is simulated with a setTimeout() call. It's common to dispatch
an action before initiating any asynchronous behavior so that your application state knows that some
data is being requested (this state could display a loading icon, for instance). Then, once you receive the
data, you dispatch another action which carries the data as a payload along with information that the
action is completed.
Remember that you're passing dispatch as a parameter to this special action creator. This is what you'll
use to dispatch your actions, you simply pass the action directly to dispatch and the middleware takes
care of the rest.
Write both dispatches in the handleAsync() action creator. Dispatch requestingData() before
the setTimeout() (the simulated API call). Then, after you receive the (pretend) data, dispatch
the receivedData() action, passing in this data. Now you know how to handle asynchronous actions in
Redux. Everything else continues to behave as before.
setTimeout(function() {
let data = {
users: ["Jeff", "William", "Alice"]
};
// dispatch received data action here
dispatch(receivedData(data));
}, 2500);
};
};
const defaultState = {
fetching: false,
users: []
};
In this lesson, you'll implement a simple counter with Redux from scratch. The basics are
provided in the code editor, but you'll have to fill in the details! Use the names that are
provided and define incAction and decAction action creators,
the counterReducer(), INCREMENT and DECREMENT action types, and finally the Redux store.
Once you're finished you should be able to dispatch INCREMENT or DECREMENT actions to
increment or decrement the state held in the store. Good luck building your first Redux app!
If you took a snapshot of the state of a Redux app over time, you would see something
like state 1, state 2, state 3,state 4, ... and so on where each state may be similar to the
last, but each is a distinct piece of data. This immutability, in fact, is what provides such
features as time-travel debugging that you may have heard about.
Redux does not actively enforce state immutability in its store or reducers, that
responsibility falls on the programmer. Fortunately, JavaScript (especially ES6) provides
several useful tools you can use to enforce the immutability of your state, whether it is
a string, number, array, or object. Note that strings and numbers are primitive values and
are immutable by nature. In other words, 3 is always 3. You cannot change the value of
the number 3. An array or object, however, is mutable. In practice, your state will probably
consist of an array or object, as these are useful data structures for representing many
types of information.
There is a store and reducer in the code editor for managing to-do items. Finish writing
the ADD_TO_DO case in the reducer to append a new to-do to the state. There are a few
ways to accomplish this with standard JavaScript or ES6. See if you can find a way to
return a new array with the item from action.todo appended to the end.
newArray is now a clone of myArray. Both arrays still exist separately in memory. If you
perform a mutation like newArray.push(5), myArray doesn't change.
The ... effectively spreads out the values in myArray into a new array. To clone an array
but add additional values in the new array, you could write [...myArray, 'new value']. This
would return a new array composed of the values in myArray and the string new
value as the last value. The spread syntax can be used multiple times in array
composition like this, but it's important to note that it only makes a shallow copy of the
array. That is to say, it only provides immutable array operations for one-dimensional
arrays.
Use the spread operator to return a new copy of state when a to-do is added
The reducer and action creator were modified to remove an item from an array based on the index of
the item. Finish writing the reducer so a new state array is returned with the item at the specific index
removed.
This creates newObject as a new object, which contains the properties that currently
exist in obj1 and obj2.
The Redux state and actions were modified to handle an object for the state. Edit the
code to return a new state object for actions with type ONLINE, which set
the status property to the string online. Try to use Object.assign() to complete the
challenge.
const defaultState = {
user: "CamperBot",
status: "offline",
friends: "732,982",
community: "freeCodeCamp"
};