Created
March 19, 2020 19:07
-
-
Save AstralJohn/2d6f1beb57ed142dda187cd37f35a7dc to your computer and use it in GitHub Desktop.
Google oAuth React Component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from "react"; | |
import { connect } from "react-redux"; | |
import { signIn, signOut } from "../actions"; | |
class GoogleAuth extends Component { | |
async componentDidMount() { | |
await window.gapi.load("client:auth2", () => { | |
window.gapi.client.init({ | |
clientId: | |
"94910912396-hlqsqje34u4hf802fv9dhf2kl5053048.apps.googleusercontent.com", | |
scope: "email" | |
}); | |
this.auth = window.gapi.auth2.getAuthInstance(); | |
this.onAuthChange(this.auth.isSignedIn.get()); | |
this.auth.isSignedIn.listen(this.onAuthChange); | |
}); | |
} | |
onAuthChange = isSignedIn => { | |
if (isSignedIn) { | |
this.props.signIn(this.auth.currentUser.get().getId()); | |
} else { | |
this.props.signOut(); | |
} | |
}; | |
onSignInClick = () => { | |
this.auth.signIn(); | |
}; | |
onSignOutClick = () => { | |
this.auth.signOut(); | |
}; | |
renderAuthButton() { | |
if (this.props.isSignedIn === null) { | |
return null; | |
} else if (this.props.auth.isSignedIn) { | |
return ( | |
<button className="ui red google button" onClick={this.onSignOutClick}> | |
<i className="icon google" /> | |
Sign Out | |
</button> | |
); | |
} else { | |
return ( | |
<button className="ui red google button" onClick={this.onSignInClick}> | |
<i className="icon google" /> | |
Sign In | |
</button> | |
); | |
} | |
} | |
render() { | |
return this.renderAuthButton(); | |
} | |
} | |
const mapStateToProps = ({ auth }) => ({ auth }); | |
export default connect(mapStateToProps, { | |
signIn, | |
signOut | |
})(GoogleAuth); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { SIGN_IN, SIGN_OUT } from "../actions/types"; | |
const INITIAL_STATE = { | |
isSignedIn: null, | |
userId: null | |
}; | |
export default (state = INITIAL_STATE, action) => { | |
const { payload, type } = action; | |
switch (type) { | |
case SIGN_IN: | |
return { ...state, isSignedIn: true, userId: payload }; | |
case SIGN_OUT: | |
return { ...state, isSignedIn: false, userId: null }; | |
default: | |
return state; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment