Prevent infinite api request in componentDidUpdate Method
class LifeCycle extends Component {
constructor(){
super()
console.log("constructor start")
this.state = {
count : 0,
data : []
}
}
getData = async() => {
const data = await fetch("https://jsonplaceholder.typicode.com/users")
const result = await data.json()
console.log(result)
this.setState({
data : result
})
}
componentDidMount(){
console.log("component life cycle start")
}
componentDidUpdate(){
this.getData()
console.log("component state is update")
}
increment = () => {
this.setState({
count : this.state + 1
}
}
render(){
console.log("render start")
return (
<div>
<h1>Count - {count}</h1>
<button onClick={this.increment}> Increment </button>
{this.state.data.map((item , index ) => (
<p key={index}>{item.name}</p>
))}
</div>
)
}
}Last updated