Answers for "why we use componentdidmount in react"

2

component did update arguments

componentDidUpdate(prevProps, prevState) {
  // only update chart if the data has changed
  if (prevProps.data !== this.props.data) {
    this.chart = c3.load({
      data: this.props.data
    });
  }
}
Posted by: Guest on October-05-2020
0

componentdidmount

import React, { Component } from 'react';

class App extends Component {

  constructor(props){
    super(props);
    this.state = {
      data: 'Jordan Belfort'
    }
  }

  getData(){
    setTimeout(() => {
      console.log('Our data is fetched');
      this.setState({
        data: 'Hello WallStreet'
      })
    }, 1000)
  }

  componentDidMount(){
    this.getData();
  }

  render() {
    return(
      <div>
      {this.state.data}
    </div>
    )
  }
}

export default App;
Posted by: Guest on June-17-2021
0

USE OF COMPONENTDIDMOUNT()

// good place to call setState here

componentDidMount(){
  this.setState({
    message: 'i got changed',
  });
}

---

// or to make request to the server

componentDidMount() {
    fetch('https://api.mydomain.com')
      .then(response => response.json())
      .then(data => this.setState({ message: data.message }));
  }
Posted by: Guest on October-15-2021
2

lifecycles if reactjs

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  componentDidMount() {  }
  componentWillUnmount() {  }
  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}
Posted by: Guest on July-07-2020

Browse Popular Code Answers by Language