Writing our first Redux parts
Let's take the first steps in using Redux for our weather app
Our First Action
Let’s write our first action! We’ll start with the location field, since it’s a very typical example. An action function in Redux returns an object with a type
and can optionally also pass some data along the way. Our changeLocation
action looks like this:
function changeLocation(location) {
return {
type: 'CHANGE_LOCATION',
location: location
};
}
This action thus has a type of 'CHANGE_LOCATION'
and passes along some data with the location
property.
That’s nice and all, but this won’t change the state automatically. We have to tell Redux what to do when this action comes in, which we do in a so-called reducer.
A reducer is a simple function that takes two arguments, the current state and the action that was dispatched:
function mainReducer(state, action) {
return state;
}
Right now, no matter what action comes in and what data it has the state will always stay the same – that’s not quite optimal, as nobody will be able to work with the app! Let’s change the location
field in the state based on the data in the action with the 'CHANGE_LOCATION'
type.
function mainReducer(state, action) {
switch (action.type) {
case 'CHANGE_LOCATION':
state.location = action.location;
return state;
}
}
What we’re doing here is mutating the state. We assign state.location
the value of action.location
. This is discouraged by Redux because it introduces potential bugs and side effects. What we instead should be doing is returning a new object which is a copy of the state!
JavaScript has a handy function called Object.assign
, which allows you to do that. Let’s take a look at the solution first:
function mainReducer(state, action) {
switch (action.type) {
case 'CHANGE_LOCATION':
return Object.assign({}, state, {
location: action.location
});
}
}
By passing in a new, empty object ({}
) as the first argument and the current state
as the second one, we create a carbon copy of the state. The third argument of the function ({
...