Reflux makes connecting to a store extremely simple. Let's refactor a React component so that the data now comes from a Reflux store and allows the data store to trigger future updates.
[00:00] To connect this simple demo up to a Reflux store, I'm first going to move this data we're displaying into a state, so this.state.message.
[00:10] Then we'll say, "getInitialState" and return message of "Hello from state." Again, this is the shorthand ES6 syntax for functions on an object. Once I refresh here, you'll see it says, "Hello from state."
[00:30] Now, I can go ahead and install Reflux. Once I have Reflux installed, I can say, "require("reflux")," and then, Reflux is what I required. Then, use Reflux to create a store, which is just going to be an object where I'm going to cut getInitialState out of the component and paste it into the store.
[00:59] Then, to hook these up together, I'll say, "var store." That's something that I can pass into mixins, which is just basically, functionality, you can mix into your components, which takes an array.
[01:13] I'll say, "Reflux.connect," and I'll say, "store." Once I save, hit refresh, it'll still work. Just to make sure it's coming from the store, I'll say, "Hello from store." Refresh again. We have "Hello from store."
[01:30] What's going on here is this Reflux.connect helper is grabbing a store. Any time it triggers an update, it's going to say, "Set state," or when it requests the getInitialState, it's going to get it from this.
[01:43] To show you how you can trigger an update, I'll go ahead and set up an init. Init with a setInterval, which takes a function. I'm using the arrow function, because I want this scoped to my store.
[02:01] I'll say, "this.trigger." Any data I pass into this.trigger, for example, an object with message on it, that says, "Something different."
[02:14] Then, we'll call this every second. I'll go ahead and hit "save." Refresh. You can see after one second, it changes to something different. To see this more in action, I'm actually going to move this out of here.
[02:30] Instead of returning an object, I'll say, "return this.data." I'll go ahead and set up a data on here, which will just start as an object with a message of "0Then, in my setInterval, I can say, "this.data.message++." Every time I trigger it, I can say, "this.data" and just send that along. Save. Refresh. You'll see "01, 2, 3" and so on. You'll notice that I didn't change anything else in the component itself. It's really connected to this store that I created.
[03:12] It's calling that set state, which is updating this.state.message every time that this.trigger gets called on the store. We get that initial state, which is just the data.message.
[03:26] Then, every second, we're updating the message. Then, we're triggering it so that we send that new data along, which, again, gets called as set state on our component.
I'm so impressed with how this guy teaches!