Skip to content

Commit

Permalink
Merge pull request #19 from ut-code/fix-authprovider
Browse files Browse the repository at this point in the history
useAuthContext()がbackから取得したユーザー情報を返すように変更
  • Loading branch information
naka-12 authored May 26, 2024
2 parents dd53000 + f7bdf92 commit 5a7a656
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 8 deletions.
4 changes: 2 additions & 2 deletions back/src/helpers/userHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,11 @@ export async function createUser({
}

// ユーザーの取得
export async function getUser(userId: number) {
export async function getUser(uid: string) {
try {
const user = await prisma.user.findUnique({
where: {
id: userId,
uid: uid,
},
});
return user;
Expand Down
6 changes: 3 additions & 3 deletions back/src/routes/users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ import { createUser, deleteUser, getUser, updateUser } from "../helpers/userHelp
const router = express.Router();

// ユーザーの取得エンドポイント
router.get("/:userId", async (req: Request, res: Response) => {
const { userId } = req.params;
router.get("/:uid", async (req: Request, res: Response) => {
const { uid } = req.params;

try {
const user = await getUser(parseInt(userId));
const user = await getUser(uid);
if (!user) {
return res.status(404).json({ error: "User not found" });
}
Expand Down
22 changes: 19 additions & 3 deletions front/src/provider/AuthProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
import { User, getAuth, onAuthStateChanged } from "firebase/auth";
import { getAuth, onAuthStateChanged } from "firebase/auth";
import { createContext, useContext, useEffect, useState } from "react";

interface User {
id: number;
uid: string;
name: string;
email: string;
}

const AuthContext = createContext<User | null | undefined>(undefined);

export default function AuthProvider({
Expand All @@ -9,12 +16,21 @@ export default function AuthProvider({
children: React.ReactNode;
}) {
const [user, setUser] = useState<User | null | undefined>(undefined);
async function getUserData(uid: string): Promise<User> {
try {
const response = await fetch(`http://localhost:3000/users/${uid}`);
const data = await response.json();
return data;
} catch (error) {
throw error;
}
}

useEffect(() => {
try {
const auth = getAuth();
return onAuthStateChanged(auth, (user) => {
setUser(user);
return onAuthStateChanged(auth, (firebaseUser) => {
getUserData(firebaseUser!.uid).then((user) => setUser(user));
});
} catch (error) {
setUser(null);
Expand Down

0 comments on commit 5a7a656

Please sign in to comment.