Reflux - Creating Your First Action in React

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet
Published 10 years ago
Updated 6 years ago

Reflux uses Actions to tell the Stores when to update. We will wire Actions and Stores together to create a simple updatable age field React component.

[00:00] I'm going to use this person, and render him out here in a h2 image tag, by using p, and assigning that to this.state.person. The way we do this is by using the person inside of get initial state, where I return an object with a person property. This is ES6, so ES5 would look like this, where I have a person key, assigned to that person object. But, in ES6, we don't need that, as long as those names match up, we can just say, object person.

[00:31] Person here is just assigned to p, and I use p.name and p.avatar to render him out. I'll go ahead and add his age through an h2 of p.age. What we're going to do is, any time we click on this, we are going to update it to a random number, using actions.

[00:51] The way that we do this, is by saying Reflux.createActions, and we will pass in an array of strings. We'll pass in one of updateAge, and this will return an actions object which we can use, so, we'll say var actions, and assign that.

[01:08] We can take our actions, and put them in the store, by saying listenables, this takes an array of actions. You can pass in multiples actions in here. We'll just use this one. We can say, onUpdateAge, and UpdateAge in this string by convention, just has to match this UpdateAge with, on prepended to the name of it, and then they map up automatically. The string matches up to the name.

[01:40] We'll say person.age is Math.random*100. Then, we can just say, this.trigger, and pass in an object with that person on it, and that's how you trigger a state change from your store, just like we've shown before. Trigger, triggers the this.setState.

[02:04] Make sure your mixins are hooked up through Reflux.connectstore. Now, we can add the onClick, and pass in the actions.updateAge. We click on 30, and we get some new random ages, because the state is changing. The click is triggering updateAge, and that matches the name of the string, passed into the actions, which is mapped into the listenables, into the store, and onUpdateAge by convention matches that updateAge string. Then person.Age is a random number, it's triggered which sets the state, and we're done.