Skip to content

Instantly share code, notes, and snippets.

@elliette
Last active May 31, 2017 16:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elliette/bfc61efc946cad7db2f07ebe5195db5c to your computer and use it in GitHub Desktop.
Save elliette/bfc61efc946cad7db2f07ebe5195db5c to your computer and use it in GitHub Desktop.

A Walk Through of React-Redux Data Flow Using Puppy Book

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!

Step One - How will your state change?

Think about how store state is going to change. Then write an action, an action creator, and modify your reducer accordingly.

Action:

const ADD_PUPPY = 'ADD_PUPPY';

Action creator:

const addPuppy = puppy => ( { type: ADD_PUPPY, puppy: puppy } );

And inside the reducer:

case ADD_PUPPY:
	newState = [ ...state, action.puppy ];
	break;

Step Two - Container Time

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.

Step Three - Mapping to Props

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.

Mapping State:

const  mapStateToProps = (state) => { 
 	return {
    		allPuppies : state.allPuppies
  	}
}

Mapping a dispatcher:

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)

Step Five - Make your component

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment