Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

188
Views
How to update state with react js with componentDidUpdate and setState?

How to update the data with react js eg a user writes a comment how to make this messages show up to all other users? I used setState in componentDidUpdate with a stop condition but it doesn't work. If i don't make a condition, it work correctely but with infinite loop.

componentDidUpdate(prevProps, prevState) { 
console.log("1" + prevState.changeRepComm.toString())
console.log("2" + this.state.changeRepComm.toString())
 if (prevState.changeRepComm !== this.state.changeRepComm ) {
  if (this.updateTimer) return;     
      this.updateTimer = setTimeout(() => {
      //lister response comments
     fetch('/api/ReponseCommentaire/listerReponseCommentaire', {
      method: "GET",
      headers: {
        'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
        'Content-Type': 'application/json'
      }
    })
      .then(response => response.json())
      .then(response => {
        console.log('Ajouter response:' + JSON.stringify(response))
        this.setState({ ...this.state, reponseCommentaires: response });
      })
      .catch((err) => {
        console.log('fetch failed => ', err);
      })

  }, 1000);

} }

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

If your looking to update every second, you can initialize a timer when component mounts.

componentDidMount(prevProps, prevState) { 
    if (this.updateTimer) { return; }  

    this.updateTimer = setInterval(() => {
      fetch('/api/ReponseCommentaire/listerReponseCommentaire', {
        method: "GET",
        headers: {
          'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
          'Content-Type': 'application/json'
        }
      })
      .then(response => response.json())
      .then(response => {
        this.setState({
          ...this.state,
          reponseCommentaires: response,
        });
      })
      .catch((err) => console.log('fetch failed => ', err) )

    }, 1000);
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!