Last active
February 28, 2023 23:38
-
-
Save matarillo/4780413ca26cb92d6bf22f6a9821786c to your computer and use it in GitHub Desktop.
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 { useState, useEffect } from "react"; | |
import { useAuth } from "react-oidc-context"; | |
const [UNAUTHENTICATED, AUTHENTICATING, AUTHENTICATED] = ["unauthenticated" , "authenticating", "authenticated"]; | |
function Content(props) { | |
switch (props.authState) { | |
case UNAUTHENTICATED: | |
return ( | |
<p> | |
<button className="button" onClick={props.login}> | |
Log in | |
</button> | |
</p> | |
) | |
case AUTHENTICATING: | |
return ( | |
<p>Loading...</p> | |
) | |
case AUTHENTICATED: | |
return ( | |
<> | |
<h1 className="title">Hello, {props.user.name}!</h1> | |
<p> | |
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do | |
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad | |
minim veniam, quis nostrud exercitation ullamco laboris nisi ut | |
aliquip ex ea commodo consequat. Duis aute irure dolor in | |
reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla | |
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in | |
culpa qui officia deserunt mollit anim id est laborum. | |
</p> | |
<p> | |
<button className="button" onClick={props.logout}> | |
Log out | |
</button> | |
</p> | |
</> | |
) | |
} | |
} | |
export default function Example() { | |
const auth = useAuth(); | |
const login = () => auth.signinRedirect(); | |
const logout = () => auth.removeUser(); | |
const [user, setUser] = useState(null); | |
const authState = | |
(!auth.isAuthenticated) ? UNAUTHENTICATED : | |
(user == null) ? AUTHENTICATING : | |
AUTHENTICATED; | |
useEffect(() => { | |
if (authState !== AUTHENTICATING) { | |
return; | |
} | |
(async () => { | |
try { | |
const token = auth.user?.access_token; | |
const response = await fetch("https://api.atlassian.com/me", { | |
headers: { | |
Authorization: `Bearer ${token}`, | |
}, | |
}); | |
const user = await response.json(); | |
setUser(user); | |
} catch (e) { | |
console.error(e); | |
} | |
})(); | |
}, []); | |
return ( | |
<section className="container"> | |
<Content authState={authState} user={user} login={login} logout={logout} /> | |
</section> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
動かないこともないけど、Exampleをマウントし直すとuserが消去されるし、そのたびfetchしているので、上位コンポーネントでfetchしたデータを引き回した方がいいのかも。(SWRを使うのは違うっぽい)