N
N
Nikita Gimon2018-04-24 17:28:21
React
Nikita Gimon, 2018-04-24 17:28:21

What is the reason for getting error in setState?

I get an error: 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. Tell me how can I fix it?

import React from 'react';
import './App.css';

export class Clock extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            days: 0,
            hours: 0,
            minutes: 0,
            seconds: 0
        }
    }

    componentWillMount(){
        this.getTimeUntil(this.props.deadline);
    }

    componentDidMount() {
        setInterval(
            () => this.getTimeUntil(this.props.deadline), 1000
        );
    }
    
    getTimeUntil = (deadline) => {
        const  time = Date.parse(deadline) - Date.parse(new Date());
        const  seconds = Math.floor((time / 1000) % 60);
        const  minutes = Math.floor((time / 1000 / 60) % 60);
        const  hours = Math.floor(time / (1000 * 60 * 60) % 24);
        const days = Math.floor(time /(1000 * 60 * 60 * 24));

        this.setState({days, hours, minutes, seconds});
    }


    render() {
        this.getTimeUntil(this.props.deadline);

        return (
            <div className="Data clearfix">
         <ul>
           <li className="Datad"><h3>{this.state.days} Days</h3></li>
           <li className="Datad"><h3>{this.state.hours} Hours</h3></li>
           <li className="Datad"><h3>{this.state.minutes} Minutes</h3></li>
           <li className="Datad"><h3>{this.state.seconds} Seconds</h3></li>
         </ul>
         </div>
        )
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton, 2018-12-11
@prod357

The render() method calls getTimeUntil() which calls setState() which calls render() and so on.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question