I am working with React and I am trying to understand the life cycle. I am making the componentWillMount method to get the props I need before rendering. I need to know how to update state when loading a view.
All I'm trying to do is get a GET request to get a list of casino dealers. Basically, I skip 1 or 2 steps that are intended to display a list of dealers in the DOM
I will show what I do with my code and after that I will explain what I want
Part of the action
getDealerActions.js
class GetDealersActions { constructor () { this.generateActions('dealerDataSuccess', 'dealerDataFail'); } getDealers (data) { const that = this; that.dispatch(); axios.get('someroute/get-dealers/get-dealers') .then(function success (response) { that.actions.dealerDataSuccess({...response.data}); }) } };
then we go to the stores
getDealersStore.js
class GetDealersStore { constructor () { this.state = { dealerData : null, }; } @bind(GetDealersActions.dealerDataSuccess) dealerDataSuccess (data) { this.setState({ dealerData : data, }); console.log(this.state.dealerData); } }
in this case, that console.log(this.state.dealerData); returns something like this, which is exactly what I need
Object {dealersData: Array[3]}
problems are part of it, honestly, because I donβt know how to process the data here.
@connectToStores export default class Dealers extends Component { static contextTypes = { router : React.PropTypes.func, } constructor (props) { super(props); this.state = {} } static getStores () { return [ GetDealersStore ]; } static getPropsFromStores () { return GetDealersStore.getState(); } componentWillMount () { console.log('@@@', this.props); GetDealersActions.getDealers(); } render () { console.log('>>>', this.props); let content; if (this.state.dealerData) { content = this.state.dealerData.map((item) => { return <div key={item.CardId}>{item}</div>; }); } else { content = <div>Loading . . .</div>; } return ( <div> <div>{content}</div> </div> ); } }
all i get here is <div>{content}</div> is Loading . . . Loading . . . because this.state fits as Object {}
The strange situation that I get here is that this view is executed twice, the first time is rendering, and console.log('>>>', this.props); returns this >>> Object {params: Object, query: Object} , and the second time it displays, it starts this >>> Object {params: Object, query: Object, dealerData: Object} , which is what I need.
So why is componentWillMount waiting for a rendering method to get fired?