So you've finished Puppy Book but want to take it to the next level- let's walk through the data flow for adding a puppy to our store state!
Think about how store state is going to change. Then write an action, an action creator, and modify your reducer accordingly.
const ADD_PUPPY = 'ADD_PUPPY';
const addPuppy = puppy => ( { type: ADD_PUPPY, puppy: puppy } );
case ADD_PUPPY:
newState = [ ...state, action.puppy ];
break;
If you need to make a new component, then first create its container. Otherwise, find the container for the component this new action will be used in. In Puppy Book, adding a puppy would most likely warrant a new component, which would be a form to input the new puppy info into.
A side note: If we wanted to delete a puppy, would we need to make a container? Probably not! Deleting a puppy would most likely be added to the singlePuppyContainer
, or even the allPuppiesContainer
.
Inside the container, you can now map whatever state you need, and whatever dispatcher you need, to props with the two functions mapStateToProps
and mapDispatchToProps
.
const mapStateToProps = (state) => {
return {
allPuppies : state.allPuppies
}
}
Remember: a dispatcher returns a function that takes in one argument, the dispatch
funtion, and has a return value of dispatch
invoked with the action creator you wrote.
const mapDispatchToProps = (dispatch) => {
return {
addPuppyDispatcher : (puppy) => dispatch(addPuppy(puppy))
}
}
You can now connect
your action and your state to your component with the connect
function.
connect(mapStateToProps, mapDispatchToProps)(addPuppyComponent)
That component that you just invoked with connect? It's time to make it! From the example above, on your props object in this new addPuppyComponent
you should now have the array allPuppies
(which is your state) and the function addPuppyDispatcher
which will dispatch the addPuppy
action and update your state.