Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FirebaseUIを使ってログイン周りを作成 #1

Merged
merged 9 commits into from
May 8, 2022
39 changes: 39 additions & 0 deletions components/SignInOrSignOutButton.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import NextLink from "next/link";
import { Box, Spinner, VStack } from "@chakra-ui/react";
import { useAuthState } from "../hooks/useAuthState";
import { getAuth, signOut } from "firebase/auth";

const SignInOrSignOutButton: React.FC = () => {
const { isSignedIn, isLoading } = useAuthState();

if (isLoading) return <Spinner />;

return (
<VStack>
{isSignedIn ? (
<button onClick={() => signOut(getAuth())}>
ログアウト(※ ログインはないよ)
</button>
) : (
<NextLink href={"/signup"}>
<Box
as="span"
textAlign="center"
marginTop={4}
cursor="pointer"
backgroundColor="teal.500"
color="white"
fontSize={16}
paddingX={6}
paddingY={2}
borderRadius={10}
>
サインイン
</Box>
</NextLink>
)}
</VStack>
);
};

export default SignInOrSignOutButton;
27 changes: 27 additions & 0 deletions components/SignInform.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { EmailAuthProvider, getAuth } from "firebase/auth";
import { useEffect, useState } from "react";
import StyledFirebaseAuth from "react-firebaseui/StyledFirebaseAuth";

const uiConfig = {
signInFlow: "popup",
signInOptions: [EmailAuthProvider.PROVIDER_ID],
signInSuccessUrl: "/",
};

export const SignInForm: React.FC = () => {
const [renderAuth, setRenderAuth] = useState(false);

useEffect(() => {
if (typeof window !== "undefined") {
setRenderAuth(true);
}
}, []);

return (
<div>
{renderAuth ? (
<StyledFirebaseAuth uiConfig={uiConfig} firebaseAuth={getAuth()} />
) : null}
</div>
);
};
51 changes: 51 additions & 0 deletions hooks/useAuthState.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { useEffect, useState } from "react";
import { getAuth, onAuthStateChanged } from "firebase/auth";

/**
* useAuthState フックの戻り値の型。
*/
export type AuthState = {
isSignedIn: boolean;
isLoading: boolean;
userId: string | undefined;
userName: string | undefined;
};

/**
* useAuthState が返す初期値。
* Next.js のサーバーサイドレンダリング時もこの値になる。
*/
const INITIAL_AUTH_STATE: AuthState = {
isSignedIn: false,
isLoading: true,
userId: undefined,
userName: undefined,
};

/**
* ユーザーのサインイン状態を取得するためのカスタムフック。
*/
export const useAuthState = (): AuthState => {
const [authState, setAuthState] = useState(INITIAL_AUTH_STATE);

// サインイン状態の変化を監視する
useEffect(() => {
const unsubscribe = onAuthStateChanged(getAuth(), (user) => {
if (user) {
setAuthState({
isSignedIn: true,
isLoading: false,
userId: user.uid,
userName: user.displayName || undefined,
});
} else {
setAuthState({ ...INITIAL_AUTH_STATE, isLoading: false });
}
});

// ページ遷移時にサインイン状態の監視を解除
return () => unsubscribe();
}, []);

return authState;
};
5 changes: 2 additions & 3 deletions lib/firebase.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
import "firebase/compat/auth";

const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
Expand All @@ -11,5 +11,4 @@ const firebaseConfig = {
measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID,
};

const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
export const app = initializeApp(firebaseConfig);
6 changes: 4 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,12 @@
"@emotion/react": "^11",
"@emotion/styled": "^11",
"firebase": "^9.6.11",
"firebaseui": "^6.0.1",
"framer-motion": "^6",
"next": "12.1.4",
"react": "18.0.0",
"react-dom": "18.0.0"
"react": "17.0.2",
"react-dom": "17.0.2",
Comment on lines +20 to +21
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📝 react18にするとfirebaseuiでエラーになるため、バージョンを下げることにした

ref: firebase/firebaseui-web-react#172

"react-firebaseui": "^6.0.0"
},
"devDependencies": {
"@types/node": "17.0.23",
Expand Down
1 change: 1 addition & 0 deletions pages/_app.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { ChakraProvider } from "@chakra-ui/react";
import type { AppProps } from "next/app";
import "../lib/firebase";

function MyApp({ Component, pageProps }: AppProps) {
return (
Expand Down
23 changes: 3 additions & 20 deletions pages/index.tsx
Original file line number Diff line number Diff line change
@@ -1,31 +1,14 @@
import type { NextPage } from "next";
import NextLink from "next/link";
import { Box, chakra, Container, VStack } from "@chakra-ui/react";
import { chakra, Container } from "@chakra-ui/react";
import SignInOrSignOutButton from "../components/SignInOrSignOutButton";

const Home: NextPage = () => {
return (
<Container maxW="md" padding={10} textAlign="center">
<chakra.h1 textAlign="center" fontSize={24}>
Homeページだよ
</chakra.h1>
<VStack>
<NextLink href={"/login"}>
<Box
as="span"
textAlign="center"
marginTop={4}
cursor="pointer"
backgroundColor="teal.500"
color="white"
fontSize={16}
paddingX={6}
paddingY={2}
borderRadius={10}
>
ログイン
</Box>
</NextLink>
</VStack>
<SignInOrSignOutButton />
</Container>
);
};
Expand Down
7 changes: 0 additions & 7 deletions pages/login.tsx

This file was deleted.

12 changes: 12 additions & 0 deletions pages/signup.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import type { NextPage } from "next";
import { SignInForm } from "../components/SignInform";

const Signup: NextPage = () => {
return (
<div>
<SignInForm />
</div>
);
};

export default Signup;
Loading