Skip to content

Instantly share code, notes, and snippets.

@sanderdebr
Created February 1, 2020 10:16

Revisions

  1. sanderdebr created this gist Feb 1, 2020.
    42 changes: 42 additions & 0 deletions withAuthentication.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,42 @@
    import React from 'react';

    import AuthUserContext from './context';
    import { withFirebase } from '../Firebase';

    const withAuthentication = Component => {
    class WithAuthentication extends React.Component {
    constructor(props) {
    super(props);

    this.state = {
    authUser: null,
    };
    }

    componentDidMount() {
    this.listener = this.props.firebase.auth.onAuthStateChanged(
    authUser => {
    authUser
    ? this.setState({ authUser })
    : this.setState({ authUser: null });
    },
    );
    }

    componentWillUnmount() {
    this.listener();
    }

    render() {
    return (
    <AuthUserContext.Provider value={this.state.authUser}>
    <Component {...this.props} />
    </AuthUserContext.Provider>
    );
    }
    }

    return withFirebase(WithAuthentication);
    };

    export default withAuthentication;