Khoa Võ Đức
Khoa Võ Đức

Reputation: 53

what happen with my componentDidUpdate in reactjs?

this is file app.js

...
constructor(props) {
    super(props);
    this.state = {
      todoLists: [],
      inputValue: "",
      currentName: "",
      todoSearch: "",
      idUpdate: "",
      loader: true
    };
  }
 componentDidUpdate(){
    this.setState({
      loader: true
    })
  }
  componentDidMount() {
    axios
      .get("https://5ec912d99ccbaf0016aa8b6f.mockapi.io/todoLists")
      .then((res) => {
        this.setState({
          loader: false,
          todoLists: res.data
        });
      });
  }
...

i added componentDidUpdate in my App but it message : Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

Upvotes: 0

Views: 76

Answers (3)

Sugumar K
Sugumar K

Reputation: 204

Hi try this way to avoid maximum loop executions.

import React from "react";
import axios from "axios";
import "./styles.css";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      todoLists: [],
      loader: true
    };
  }
  componentDidMount() {
    this.setState({ loader: true });
    axios
      .get("https://5ec912d99ccbaf0016aa8b6f.mockapi.io/todoLists")
      .then(res => {
        console.log(res.data);
        this.setState({
          loader: false,
          todoLists: res.data
        });
      });
  }
  render() {
    const { loader } = this.state;
    return (
      <div>
        {loader
          ? "Loading"
          : this.state.todoLists.map(res => {
              return (
                <ul key={res.id}>
                  <li>{res.id}</li>
                  <li>{res.name}</li>
                </ul>
              );
            })}
      </div>
    );
  }
}

export default App;

Upvotes: 0

Nakul Malhotra
Nakul Malhotra

Reputation: 131

So, you're updating something in componentDidUpdate that is in the state, and updating the state triggers this, so it's in an infinite loop, could you explain what you're trying to do I could give a solution?

Upvotes: 0

Arpit Vyas
Arpit Vyas

Reputation: 2227

componentDidUpdate Call every time when set state happen so, you have to remove setState in didUpdate or call based on condition like this ..

componentDidupdate(){
 //check this is called every time when render executed .
 console.log('did update');
  if(some condition){
   this.setState({});
 }
}

Upvotes: 3

Related Questions