Create Redux Dispatch Functions From Action Creators with bindActionCreators

Andy Van Slaars
InstructorAndy Van Slaars

Share this video with your friends

Send Tweet
Published 4 years ago
Updated 3 years ago

In this lesson we’ll look at the bindActionCreators helper method provided by Redux to eliminate some boilerplate code in our React application. Currently we have a function that takes in a value and calls an action creator. This pattern is extremely common in Redux and we will see how bindActionCreators can help us cut down on some bloat.

[00:00] Right now, we have a single function that handles dispatching actions. It takes in a value and uses that in a call to an action creator. This action creator is wrapped in a call to store it at dispatch. This is a very common pattern in Redux. Because it's so common Redux provides a function to help us cut down in the boiler plate code needed to create these functions.

[00:18] We're going to pull that function in. I'm going to jump up here and I'm going to import bind action creators and that's going to come in from the Redux library. Then I'm going to take the current todo change handler function, I'm just going to comment that out.

[00:37] I'm going to define a constant, I'm going to call actions. I'm going to set that actions constant to equal a call to bind action creators. Bind action creators is going to take an object followed by a reference to our dispatch function which we're getting form the store.

[00:57] Our object is going to be key value pairs where each key represents the name of the function we want to call to dispatch an action. In our case, it's going to be todo change handler. Then the value is going to be the action creator that we want our value passed to. In this case it's going to be updatecurrent.

[01:16] Now that we've created that and we're assigning this back to actions, actions is going to have our todo change handler. I'm going to come down here and update this reference to call that on actions. We'll save that. Then I should be able to go into the browser and everything should still work.

[01:33] Now I can come back over here and what I can do is I could come up here and I could get rid of this key and I could use shorthand syntax, and essentially create an object where updatecurrent is both the key and the value. I'll clean up this commented out code.

[01:49] Then because we've done this, that means that actions is no longer going to have anything called todo change handler, but it will have a function called updatecurrent that will dispatch our action. I could do that and save it and back in the browser I could just verify that everything still works and it still accepts characters, so our update has occurred.

Andrew Fritz
Andrew Fritz
~ 4 years ago

This should happen before the previous lesson.