how to update state before render react code example
Example 1: react lifecycle example
class Test extends React.Component {
constructor() {
console.log('Constructor')
super();
this.state = {
count: 0
};
}
componentDidMount() {
console.log("component did mount");
}
componentDidUpdate() {
console.log("component did update");
}
onClick = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
console.log("render");
return (
<div>
Hello Test
<button onClick={this.onClick}>
{this.state.count}
</button>
</div>
);
}
}
//--for first time
//Constructor
//render
//component did mount
//--for any update
//render
//component did update
Example 2: react set state before render
componentDidMount() {
this.setState({
thing: [
{
status: "running",
test: "testing"
}
]
});
}
render() {
return (
<div>
{this.state.thing.length > 0? <h1 className="mt-5 mb-5">{ this.state.thing[0].status }</h1>: null
}
<button className="mt-5" onClick={ this.handleUpdate } value="not running">
Click to change
</button>
</div>
);
}