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 ...