feat: session handling

This commit is contained in:
Kyle Gill
2019-03-27 15:19:50 -06:00
parent 8f13a5c1f1
commit dcb757fc07
3 changed files with 54 additions and 0 deletions

View File

@@ -0,0 +1,5 @@
import React from "react";
const AuthUserContext = React.createContext(null);
export default AuthUserContext;

View File

@@ -0,0 +1,4 @@
import AuthUserContext from "./context";
import withAuthentication from "./withAuthentication";
export { AuthUserContext, withAuthentication };

View File

@@ -0,0 +1,45 @@
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: JSON.parse(localStorage.getItem("authUser"))
};
}
componentDidMount() {
this.listener = this.props.firebase.auth.onAuthStateChanged(
authUser => {
localStorage.setItem("authUser", JSON.stringify(authUser));
this.setState({ authUser });
},
() => {
localStorage.removeItem("authUser");
this.setState({ authUser: null });
}
);
}
componentWillUnmount() {
this.listener();
}
render() {
return (
<AuthUserContext.Provider value={this.state.authUser}>
<Component authUser={this.state.authUser} {...this.props} />
</AuthUserContext.Provider>
);
}
}
return withFirebase(WithAuthentication);
};
export default withAuthentication;