Two-Way Data Binding with Meteor and React

So Meteor uses getMeteorData() instead of getInitialState()` so how do we do bindings? Considering this user profile’s surname:

...

getMeteorData() {
 return {
   u = Meteor.user()
 }
},

componentRender() {
  let instance = this;
  // there is no way you can have two-way bindings here
  return(<div><input value={instance.data.user.profile.surname }</div>)
},

render() {
 return(<div>{this.data.user ?  this.componentRender() : <p>Loading...</p>}</div>)
}

...

How do you write an onChange function for this? I only know the setState's way of doing things.

Actually, getMeteorData is reactive, you register your reactive data sources in there, and if they change, the component will refresh. What you have there should be working already.

You know how in React when you change the state, it calls render() again?

Meteor’s mixin called ReactMeteorData does the same thing. When your data changes in getMeteorData, it’ll call render() again.

In Meteor-land, just focus on getting the value into the database. The UI will refresh itself.

It works but the user cannot change the name of the input field. I maybe writing more code but I have found a way and wrote this:

If you’re using React, I’d really recommend picking up Redux. It’s not a shallow learning curve (took me a week?) but it really cleans up your components and how meteor (or any backend library) interacts with them.

E.g
I have my getMeteorData() in a parent component (line 17)
I use this to push all subscribed data to my single, immutable state store (line 42)
And when the state changes, it passes all the new changes down to the components that require it via props.
https://github.com/mordra/cotwmtor/blob/master/modules/game/index.js

React has introduced pure components and Redux’s pattern words hand in hand with these. My components don’t have states and they don’t have any side effects (e.g they don’t call getMeteorData). This way, their resulting render is a pure function of the props they are passed and thus are unit testable too.

@mordrax Seems like a lot of work. A week you say? I’ll see…

Give this guy 10 minutes of your life:

If you’re not blown off your socks in that time, then perhaps I won’t recommend you go through the rest of it. Redux is one simple idea, with alot of different implications once you start thinking in that way.

I can personally say it’s worth it, for my project, it’s crystal clear how components get their data, push events back into the state and how this then communicates with meteor. The closest thing that comes to it is Session but with the adv of ReactiveDict/Var of not having your component state pollute the global state.

But checkout his videos, if you’re not convinced within the first 10 mins, then it’s only 10 mins of your life that you won’t get back :wink:

1 Like

I’m on it. Loving it so far (videos)!

1 Like