Skip to content

Instantly share code, notes, and snippets.

@manakuro
Last active January 17, 2020 08:10
Show Gist options
  • Save manakuro/2b954cc84734ba224220b29d29907e3e to your computer and use it in GitHub Desktop.
Save manakuro/2b954cc84734ba224220b29d29907e3e to your computer and use it in GitHub Desktop.
// ...
type User = {
id: string
uuid: string
name: string
email: string
createdAt: string
updatedAt: string
deletedAt: string
}
const SignUp: React.FC = () => {
// ...
const createUser = useCallback(
async (params: { email: string | null; uuid: string }) => {
return await api.post<User>(`${API_URL}/api/users`, params)
},
[],
)
const setAPIToToken = useCallback(
async (fb: firebase.auth.UserCredential) => {
const idToken = await fb.user?.getIdToken()
if (!idToken) {
console.warn('[Firebase error]: idToken is not provided')
return
}
api.setToken(idToken)
},
[],
)
const handleSignUpWithGitHub = useCallback(async () => {
const provider = new firebase.auth.GithubAuthProvider()
try {
const currentUser = await firebase.auth().currentUser
const res = currentUser
? await currentUser.linkWithPopup(provider)
: await firebase.auth().signInWithPopup(provider)
await setAPIToToken(res)
if (!currentUser) {
const firebaseUser = res.user as firebase.User
const user = await createUser({
email: firebaseUser.email,
uuid: firebaseUser.uid,
})
console.log('user: ', user)
} else {
// maybe get user through API
}
} catch (err) {
// error handling
console.error(err)
}
}, [createUser, setAPIToToken])
const handleSubmit = useCallback(
async (e: SyntheticEvent) => {
e.preventDefault()
const { email, password } = state
try {
const res = await firebase
.auth()
.createUserWithEmailAndPassword(email, password)
await setAPIToToken(res)
const firebaseUser = res.user as firebase.User
const user = await createUser({
email: firebaseUser.email,
uuid: firebaseUser.uid,
})
console.log('user: ', user)
} catch (e) {
// error handling
console.error(e)
}
},
[createUser, setAPIToToken, state],
)
// ...
}
export default SignUp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment