Tanmoy Sarker
Tanmoy Sarker

Reputation: 1266

Invariant Violation: Maximum update depth exceeded in React Native

I have a React Native component where I need to use ComponentDidMount. Also in ComponentDidMount i'm using setStatebecause I am not sure of any other way to solve my purpose. I guess for this reason I am getting the error: Invariant Violation: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. Although i'm not using componentWillUpdate or componentDidUpdate. Here's the code I have:

   currentUsers=()=>{
        let dbRef = firebase.database().ref('Users');
        dbRef.on('child_added', (val)=>{
            let person = val.val();
            person.phone = val.key;
            this.setState((prevState)=> {
                return {
                    users: [...prevState.users, person]
                }
            })
        })
    }

    componentWillMount(){
      this.currentUsers();
    }

What can I do to resolve the error?

Upvotes: 0

Views: 102

Answers (2)

Gaurav Roy
Gaurav Roy

Reputation: 12215

so , the error was basically calling a func in the the render method which calls the setState again , and hence an infinite loop. It's always advisable to use anonymous function while calling in the render method. So replacing

onChangeText={this.handleChange('textMessage')} to onChangeText={() =>this.handleChange('textMessage')}

Worked for you. Hope that helps.

Upvotes: 1

Dagur Leó
Dagur Leó

Reputation: 708

Could you provide code for the whole Class component?

Upvotes: 0

Related Questions