Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ComponentDidUpdate() data from the api with new data

Being new to react, I saw a similar example but they were not clearly explained and I didn't understand how to solve this problem. I have an API, the new data is posted to the API. ComponentDidMount() will initiate the data from the API first time. I went through the documentation and saw that componentDiUpdate() will always re-render the page if the new data is added.

This is my code so far:

constructor(props){
  super(props);
  this.state = {
    newData: [],
    dataApi: this.props.getAllData() //method that is using GET_ALL_DATA actions/reducers using fetch(get)
  }
}
// it gets the data
componentDidMount() {
  this.state.dataApi
}

componentDidUpdate(prevProps, prevState){
  this.state.dataApi.then(data => {
    if(prevProps.data != this.props.data) {
      this.setState({newData: data});
    }
  }
}

ComponentDidUpdate() errors:

Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.

How can I fix this problem? by getting the new data from the API when someone makes a post request? Thanks

like image 328
Mihail Avatar asked Mar 07 '26 01:03

Mihail


2 Answers

Solved the problem, thanks everyone: Solution to the problem will be:

this.state = {
   allData: [],
   isSubmitted: false
}

async componentDidUpdate(prevProps, prevState){
  if(this.mounted && this.state.isSubmitted){
     const allData = await this.props.getAllData();
     this.setState({isSubmitted: false,
                  allData: allData.data })
  }

componentDidMount(){ 
   this.mounted=true
}

componentWillUnmount() {
   this.mounted = false; 
}

functionAddDataToApi(){
   // some logic
   this.setState({isSubmitted: true})
}
like image 189
Mihail Avatar answered Mar 09 '26 15:03

Mihail


The componentDidMount() lifecycle method gets called once only when your component is rendered for the first time.

In your constructor(), you don't need to put a promise on your state. Instead you can remove dataApi and just call the method directly. In componentDidMount(), you'll make your API call. When the API call has finished, you can use this.setState().

The componentDidUpdate method gets called every time one of your prop or state values gets updated. As such, it is a bad idea to update state within it as you risk infinitely looping.

constructor(props){
      super(props);
      this.state = {
           newData: [], 
      };
}

// it gets the data
componentDidMount() {
    this.props.getAllData().then(data => {
        this.setState({
            newData: data,
         });
    });
}
like image 43
Toby Mellor Avatar answered Mar 09 '26 13:03

Toby Mellor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!