Created
December 14, 2020 11:35
-
-
Save jhackett1/85417d4263afe1d6d7bb261763946b9b to your computer and use it in GitHub Desktop.
A React context showing how you might manage authentication
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, { createContext, useContext } from "react" | |
import useSWR from "swr" | |
const AuthContext = createContext(false) | |
export const AuthProvider = (props) => { | |
const { data, error, mutate } = useSWR(`/api/v1/auth/me`) | |
const googleLogIn = async googleData => { | |
const res = await fetch("/api/v1/auth/google", { | |
method: "POST", | |
body: JSON.stringify({ | |
token: googleData.tokenId | |
}), | |
headers: { | |
"Content-Type": "application/json" | |
} | |
}) | |
const data = await res.json() | |
if(data.error) throw new Error(data.error) | |
mutate() | |
} | |
const logOut = async () => { | |
await fetch("/api/v1/auth/logout", { | |
method: "DELETE" | |
}) | |
mutate() | |
} | |
return( | |
<AuthContext.Provider value={{ | |
user: data, | |
error: error, | |
googleLogIn: googleLogIn, | |
logOut: logOut | |
}} {...props}/> | |
) | |
} | |
export const useAuth = () => useContext(AuthContext) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment