Something strange happens, I read the React docs and they talk about the life cycle and how you can do something before your component is rendered. I try, but everything I try fails, the component always renders first after calls to componentenWillMount, .. didMount, etc., And after calling these functions, the rendering is done again.
I need to load the data first to fill this state, because I do not want the initial state to be null , I want it with the data since the initial rendering.
I use Flux and Alt, here
act
@createActions(flux) class GetDealersActions { constructor () { this.generateActions('dealerDataSuccess', 'dealerDataFail'); } getDealers (data) { const that = this; that.dispatch(); axios.get(`${API_ENDPOINT}/get-dealers/get-dealers`) .then(function success (response) { console.log('success GetDealersActions'); that.actions.dealerDataSuccess({...response.data}); }) } }
then store
@createStore(flux) class GetDealersStore { constructor () { this.state = { dealerData : null, }; } @bind(GetDealersActions.dealerDataSuccess) dealerDataSuccess (data) { this.setState({ dealerData : data, }); } }
and component
@connectToStores export default class Dealers extends Component { static propTypes = { title : React.PropTypes.func, } static contextTypes = { router : React.PropTypes.func, } constructor (props) { super(props); this.state = { modal : false, dealerData : this.props.dealerData, } } componentWillMount () { GetDealersActions.getDealers(); this.setState({ dealerData : this.props.dealerData.dealersData, }) } static getStores () { return [ GetDealersStore ]; } static getPropsFromStores () { return { ...GetDealersStore.getState(), } } render () { return (<div> <div style={Styles.mainCont}> {!!this.props.dealerData ? this.props.dealerData.dealersData.map((dealer) => { return (<div>HERE I AM RENDERING WHAT I NEED</div>); }) : <p>Loading . . .</p> } </div> </div> ); } }
as you can see in the component part, I have this
constructor (props) { super(props); this.state = { modal : false, dealerData : this.props.dealerData, } } componentWillMount () { GetDealersActions.getDealers(); this.setState({ dealerData : this.props.dealerData.dealersData, }) }
which tells me that dealerData is undefined or can not read property of null .
All I need to do is know the technique in which I can get the data before the initial rendering happens. Therefore, I can populate state and start working with this data.