0

Into class Component I got:

state = {
       user: {}      
}

componentWillMount() {
    firebaseAuth.onAuthStateChanged((user) => {
        
        if(user) {
            this.setState({
                user: {
                    id: user.uid,
                    email: user.email
                }
            })
        }

    })
   }

But into console I got information that:

react-dom.development.js:67 Warning: componentWillMount has been renamed, and is not recommended for use. See https://reactjs.org/link/unsafe-component-lifecycles for details.

* Move code with side effects to componentDidMount, and set initial state in the constructor.
* Rename componentWillMount to UNSAFE_componentWillMount to suppress this warning in non-strict mode. In React 18.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run `npx react-codemod rename-unsafe-lifecycles` in your project source folder.

So I'm trying to fix it:

 static getDerivedStateFromProps(props, state) {  

    firebaseAuth.onAuthStateChanged((user) => {

        if(user) {
           return{               
                user:{
                    id: user.uid,
                    email: user.email
                }
           }         
        }
    })
    
    return null;
  }

But state is not updated (is not set). What Im doing wrong? How to fix it?

4est
  • 3,010
  • 6
  • 41
  • 63

1 Answers1

1

getDerivedStateFromProps will not wait for response

you have 2 solution to remove warning

1 : rename method name componentWillMount to UNSAFE_componentWillMount

2 : send request in componentDidMount

componentDidMount() {
    firebaseAuth.onAuthStateChanged((user) => {
        
        if(user) {
            this.setState({
                user: {
                    id: user.uid,
                    email: user.email
                }
            })
        }

    })
   }
Mehran Khan
  • 3,616
  • 1
  • 13
  • 10
  • for `UNSAFE_componentWillMount` Im getting as well warning, but `componentDidMount` is ok, so thank you @Mehran for help – 4est Nov 26 '20 at 13:47