Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
121
rated 0 times [  123] [ 2]  / answers: 1 / hits: 17701  / 9 Years ago, wed, october 14, 2015, 12:00:00

I am waiting the props to come up from a store named GetDealersStore, and the way I am fetching that data is with an action where I am doing this:



  componentWillMount () { GetDealersActions.getDealers(); }


I already test the app and componentWillMount() is running before the initial render where I have this



let dealerInfo;
if (this.state.dealerData) {
dealerInfo = this.state.dealerData.dealersData.map((dealer) => {
return (<div>CONTENT</div>);
})
} else {
dealerInfo = <p>Loading . . .</p>
}


but for the first second you can see <p>Loading . . .</p> in the screen which is the else in the conditional above, and then the rest of the render comes up with return (<div>CONTENT</div>); which is the if in the conditional. So, I guess, this means that the render method has been trigger twice because it keeps waiting for the data coming from the database.



The data from the database is not available at the time of the 1st render, so, how can I fetch that data before the 1st initial render occurs?


More From » reactjs

 Answers
18

You can't do this with a single component. You should follow the Container Component pattern to separate data from rendering.



let DealersContainer = React.createClass({
getInitialState() {
return {dealersData: []};
},
componentWillMount() {
GetDealersActions.getDealers();
},
render() {
let {dealersData} = this.state;
return (<div>
{dealersData.map((dealer) => {
let props = dealer;
return (<Dealer ...props />); // pass in dealerData as PROPS here
})}
</div>);
}
});


Then update your Dealer component to receive props and render the actual content.


[#64741] Monday, October 12, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cruzs

Total Points: 710
Total Questions: 113
Total Answers: 100

Location: Nepal
Member since Sat, Jul 18, 2020
4 Years ago
cruzs questions
Thu, Nov 26, 20, 00:00, 4 Years ago
Wed, Oct 28, 20, 00:00, 4 Years ago
Wed, Aug 19, 20, 00:00, 4 Years ago
Sun, Aug 2, 20, 00:00, 4 Years ago
;