Skip to content

Instantly share code, notes, and snippets.

@matarillo
Last active February 28, 2023 23:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matarillo/4780413ca26cb92d6bf22f6a9821786c to your computer and use it in GitHub Desktop.
Save matarillo/4780413ca26cb92d6bf22f6a9821786c to your computer and use it in GitHub Desktop.
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>
)
}
@matarillo
Copy link
Author

matarillo commented Feb 28, 2023

動かないこともないけど、Exampleをマウントし直すとuserが消去されるし、そのたびfetchしているので、上位コンポーネントでfetchしたデータを引き回した方がいいのかも。(SWRを使うのは違うっぽい)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment