Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Reflux - Creating Your First Action in React


    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.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    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.

    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.

    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.

    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.

    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.

    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.