The problem is that the component is being rendered twice, once with the initial state, again after the setState method in axios promise. Why is this happening and how can I solve this.
I have used both componentWillMount and componentDidMount. I, being a noob, tried hard and failed to figure out why.
export default class Dashboard extends Component{
constructor(props) {
super(props)
this.state = {
data: {
okay: 'lul'
}
}
}
componentWillMount() {
axios
.get('/api/data?param1='+this.props.location.state.param1+'¶m2='+this.props.location.state.param2)
.then(res => {
if (res.status != 401) {
if(res.err)
console.log('Error while retrieving: ', res.err)
else {
this.setState({
data: res.data.data
})
}
} else {
console.log('Unauthorized!');
}
})
}
render() {
return (
<Segment inverted vertical>
<CardContainer data={this.state.data}/>
</Segment>
)
}
}
Even basic suggestions related to react / JS / general programming is highly appreciated
this.state.datain the render method and returnnullif there's no data to show yet.setStatewill cause therendermethod to be called each time. - Håken Lidrenderis really quite cheap, since react will take care of updating the dom in a efficient manner. In some cases you might want to tweak when rerendering happens. This is discussed in the react documentation here: shouldComponentUpdate In Action - Håken Lid