Ad

React Higher Order Component To Firebase Authenticate Does Not Send Updated State To The Component

I am new to react and I am trying to authenticate with firebase in react. I have created a higher order component to essentially enrich the component with the status of the user and verify if the user is authenticated or not. Below is my WithAuthentication.js and in the component itself in the componentDidmount I am trying to check if the user isSignedin.

import React, { Component } from 'react';
import { FirebaseContext } from '../firebase';

export default WrappedComponent => {
class WithAuthentication extends Component {
    state = {
    user:null,
    isSignedin:false
    };

    componentDidMount() {

        let firebase = this.context       
        firebase.auth().onAuthStateChanged(user => {
        if (user) {
        console.log(user)  
        this.setState({ 
            user: user.providerData,
            isSignedin: true
        });
        console.log(this.state.isSignedin);
        } else {
        console.info('Must be authenticated');          
        }
    });
    }

    render() {
    return this.state.isSignedin ? (
        <WrappedComponent
        {...this.props}
        user={this.state.user}
        isSignedin={this.state.isSignedin}
        />
    ) : (
        <WrappedComponent
        {...this.props}
        user={"NOTUSER"}
        isSignedin={this.state.isSignedin}
        />
    );
    }
}
WithAuthentication.contextType =FirebaseContext
return WithAuthentication;
};

The Component file.

componentDidMount() {
let firebase = this.context
console.log(this.props);    
const db = firebase.firestore();
var turmarkers =[];

this.setState({isSignedin:this.props.isSignedin})
console.log(this.state.isSignedin);    
this.state.isSignedin  ? 
db.collection("Markets").get().then((querySnapshot) => {
  querySnapshot.forEach((doc) => {
      var mdata = doc.data()
      mdata["key"] = doc.id  
      turmarkers.push(mdata)

  });

  this.setState({
      mapdata:turmarkers
  });
 })    
:
console.log("this is not a user")    
}

In the first render the child component gets a false tag and after the WithAuthentication.js changes it's state of isSignedin to true. I expect the child component state to get updated as soon as the wrapper state gets updated. But it does not happen. The state in the wrapper component gets updated but it's not passed to the child.

I have tried directly checking the props isSignedin to see if it changes in the child and it does not.

Ad

Answer

I think i found the answer, the key is to check if the authentication is done or not and then to check if the authentication verified the user as signedin or not. Below is where it was answered.

Firebase Authentication & React

Ad
source: stackoverflow.com
Ad