SOLVED - React default state from database with ES7 class transforms


#1

Hi everyone, I’m trying to set the default state of a controlled component (range slider) with a value from the database. I’m not sure if I’m loading data incorrectly, or using the class syntax incorrectly or what.

Heres a gist if anyone has a minute and is good with React and Containers. I’m using ES7 classes after updating to Meteor 1.3.3 and installing babel class transforms plugin:

Sliding the handle back and forth updates the value in the database as expected but when the slider loads, the handle is all the way at zero. I want the initial state to be set at the value stored in the database.

The props don’t seem to be ready for state initialization on line 14 of TestPage.jsx. I’m getting an empty object.

What is the best practice to set the default state of a controlled component like this?


#2

I think I have a solution… props to the React Todos example (pun intended!):grin:

I think the main problem was that I wasn’t waiting for the subscription data to load before trying to assign props to state in TestPage. So when trying to use this.props before the constructor the data was always undefined. Also, I think React expects an array from createContainer, so in the TestContainer smart component I added a find/fetch and a ternary operator to guard against the subscription not being ready.

Now, since the data we need is being sent as an array we need to iterate over that in TestPage. Once we know we have the data in TestPage, we can assign the props to TestComponent.

Finally, in the TestComponent we initialize the Slider component state with the props.

here is the gist:

If anyone has a better idea or any tips, would love to discuss.

happy coding