Skip to content

Commit

Permalink
Merge pull request #135 from kitcc-org/66-cart-page-redirect
Browse files Browse the repository at this point in the history
カートページに自動的にリダイレクトする
  • Loading branch information
Kosei805 authored Nov 14, 2024
2 parents 41c6fb1 + 46df57c commit f519027
Show file tree
Hide file tree
Showing 12 changed files with 74 additions and 61 deletions.
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,10 @@ KITCC が所有する書籍を管理する Web アプリ
- [x] ログアウト
- カート機能
- [x] カートに追加
- [ ] カートから削除
- [ ] カートの中身を確認
- [x] カートから削除
- [x] カートの中身を確認
- 貸出履歴管理
- [ ] 貸出
- [x] 貸出
- [ ] 返却

## 使用技術
Expand Down
3 changes: 3 additions & 0 deletions frontend/app/components/books/BookCardCartButton.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Button } from '@mantine/core';
import { useNavigate } from '@remix-run/react';
import { useAtom } from 'jotai';
import { BiSolidCartAdd } from 'react-icons/bi';
import { cartAtom } from '~/stores/cartAtom';
Expand All @@ -16,8 +17,10 @@ const BookCardCartButton = ({
thumbnail,
}: BookCardCartButtonProps) => {
const [cart, setCart] = useAtom(cartAtom);
const navigate = useNavigate();
const addCart = () => {
setCart(addBooksToCart(cart, [{ id, stock, thumbnail }]));
navigate('/home/cart');
};
return (
<Button
Expand Down
5 changes: 3 additions & 2 deletions frontend/app/components/books/BookSelectedDialog.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Button, Center, Dialog, Stack, Text } from '@mantine/core';
import { useSubmit } from '@remix-run/react';
import { useNavigate, useSubmit } from '@remix-run/react';
import { useAtom } from 'jotai';
import { selectedBooksAtom } from '~/stores/bookAtom';
import { cartAtom } from '~/stores/cartAtom';
Expand All @@ -9,6 +9,7 @@ import { successNotification } from '~/utils/notification';
const BookSelectedDialog = () => {
const [selectedBook, setSelectedBook] = useAtom(selectedBooksAtom);
const [cart, setCart] = useAtom(cartAtom);
const navigate = useNavigate();

const submit = useSubmit();

Expand All @@ -32,8 +33,8 @@ const BookSelectedDialog = () => {
onClick={() => {
setCart(addBooksToCart(cart, selectedBook));
setSelectedBook([]);

successNotification('カートに追加しました');
navigate('/home/cart');
}}
>
選択中の本をカートに入れる
Expand Down
6 changes: 3 additions & 3 deletions frontend/app/routes/home._index/route.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export const action = async ({ request }: ActionFunctionArgs) => {
const session = await getSession(request.headers.get('Cookie'));

// 未ログインの場合
if (!session.has('userId')) {
if (!session.has('user')) {
session.flash('error', 'ログインしてください');
return redirect('/login', {
headers: {
Expand All @@ -77,8 +77,8 @@ export const action = async ({ request }: ActionFunctionArgs) => {
}

const cookieHeader = [
`__Secure-user_id=${session.get('userId')};`,
`__Secure-session_token=${session.get('sessionToken')}`,
`__Secure-user_id=${session.get('user')?.id};`,
`__Secure-session_token=${session.get('user')?.sessionToken}`,
].join('; ');

// prettier-ignore
Expand Down
8 changes: 4 additions & 4 deletions frontend/app/routes/home.books.$bookId.edit/route.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export const loader = async ({ params, request }: LoaderFunctionArgs) => {

const bookId = params.bookId ?? '';

if (!session.has('userId')) {
if (!session.has('user')) {
session.flash('error', 'ログインしてください');
return redirect(`/home/books/${bookId}`, {
headers: {
Expand All @@ -36,7 +36,7 @@ export const action = async ({ request }: ActionFunctionArgs) => {
const session = await getSession(request.headers.get('Cookie'));

// 未ログインの場合
if (!session.has('userId')) {
if (!session.has('user')) {
session.flash('error', 'ログインしてください');
return redirect('/login', {
headers: {
Expand All @@ -46,8 +46,8 @@ export const action = async ({ request }: ActionFunctionArgs) => {
}

const cookieHeader = [
`__Secure-user_id=${session.get('userId')};`,
`__Secure-session_token=${session.get('sessionToken')}`,
`__Secure-user_id=${session.get('user')?.id};`,
`__Secure-session_token=${session.get('user')?.sessionToken}`,
].join('; ');
const formData = await request.formData();

Expand Down
12 changes: 6 additions & 6 deletions frontend/app/routes/home.books.$bookId/route.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,14 @@ export const loader = async ({ params, request }: LoaderFunctionArgs) => {

let loansResponse = undefined;
// ログイン済みの場合は貸出履歴を取得する
if (session.has('userId')) {
if (session.has('user')) {
loansResponse = await getLoans(
{ bookId: bookId },
{
headers: {
Cookie: [
`__Secure-user_id=${session.get('userId')}`,
`__Secure-session_token=${session.get('sessionToken')}`,
`__Secure-user_id=${session.get('user')?.id}`,
`__Secure-session_token=${session.get('user')?.sessionToken}`,
].join('; '),
},
},
Expand All @@ -61,7 +61,7 @@ export const action = async ({ request }: ActionFunctionArgs) => {
const session = await getSession(request.headers.get('Cookie'));

// 未ログインの場合
if (!session.has('userId')) {
if (!session.has('user')) {
session.flash('error', 'ログインしてください');
return redirect('/login', {
headers: {
Expand All @@ -71,8 +71,8 @@ export const action = async ({ request }: ActionFunctionArgs) => {
}

const cookieHeader = [
`__Secure-user_id=${session.get('userId')};`,
`__Secure-session_token=${session.get('sessionToken')}`,
`__Secure-user_id=${session.get('user')?.id};`,
`__Secure-session_token=${session.get('user')?.sessionToken}`,
].join('; ');
const formData = await request.formData();

Expand Down
10 changes: 5 additions & 5 deletions frontend/app/routes/home.cart/route.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ export const action = async ({ request }: ActionFunctionArgs) => {
const session = await getSession(request.headers.get('Cookie'));

// 未ログインの場合
const userId = session.get('userId');
if (!userId) {
const userData = session.get('user');
if (!userData) {
return redirect('/login', {
headers: {
'Set-Cookie': await commitSession(session),
Expand All @@ -41,8 +41,8 @@ export const action = async ({ request }: ActionFunctionArgs) => {
}

const cookieHeader = [
`__Secure-user_id=${session.get('userId')};`,
`__Secure-session_token=${session.get('sessionToken')}`,
`__Secure-user_id=${session.get('user')?.id};`,
`__Secure-session_token=${session.get('user')?.sessionToken}`,
].join('; ');

// prettier-ignore
Expand All @@ -51,7 +51,7 @@ export const action = async ({ request }: ActionFunctionArgs) => {
const upsertBody: UpsertLoansBodyItem[] = selectedCartBook.map((book) => {
return {
bookId: book.id,
userId: Number(userId),
userId: userData.id,
volume: book.volume,
};
});
Expand Down
8 changes: 4 additions & 4 deletions frontend/app/routes/home.global.books.$isbn/route.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export const loader = async ({ params, request }: LoaderFunctionArgs) => {
const isbn = params.isbn ?? '';
const searchBooksResponse = await searchBooks({ isbn: isbn });
// 既に登録済みであるか確認するため
if (session.has('userId')) {
if (session.has('user')) {
const getBookResponse = await getBooks({ isbn: isbn });
if (getBookResponse.data.totalBook > 0) {
return json<LoaderData>({
Expand Down Expand Up @@ -59,7 +59,7 @@ export const action = async ({ request }: ActionFunctionArgs) => {
const session = await getSession(request.headers.get('Cookie'));

// 未ログインの場合
if (!session.has('userId')) {
if (!session.has('user')) {
session.flash('error', 'ログインしてください');
return redirect('/login', {
headers: {
Expand All @@ -69,8 +69,8 @@ export const action = async ({ request }: ActionFunctionArgs) => {
}

const cookieHeader = [
`__Secure-user_id=${session.get('userId')};`,
`__Secure-session_token=${session.get('sessionToken')}`,
`__Secure-user_id=${session.get('user')?.id};`,
`__Secure-session_token=${session.get('user')?.sessionToken}`,
].join('; ');

const requestBody = await request.json<CreateBookBody>();
Expand Down
2 changes: 1 addition & 1 deletion frontend/app/routes/home.mypage/route.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ export const loader = async ({ request }: LoaderFunctionArgs) => {
const session = await getSession(request.headers.get('Cookie'));

// 未ログインの場合
if (!session.has('userId')) {
if (!session.has('user')) {
// ログインページへリダイレクト
return redirect('/login');
}
Expand Down
66 changes: 38 additions & 28 deletions frontend/app/routes/home/route.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ import {
useNavigation,
useRevalidator,
} from '@remix-run/react';
import { getUser, logout } from 'client/client';
import { logout } from 'client/client';
import type { User } from 'client/client.schemas';
import { useAtom } from 'jotai';
import { useEffect } from 'react';
import HeaderComponent from '~/components/header/HeaderComponent';
Expand All @@ -20,35 +21,50 @@ import { userAtom } from '~/stores/userAtom';
import { errorNotification, successNotification } from '~/utils/notification';

interface LoaderData {
userId?: string;
userData?: User;
success?: string;
error?: string;
}

export const loader = async ({ request }: LoaderFunctionArgs) => {
const session = await getSession(request.headers.get('Cookie'));

const userId = session.get('userId');
const userData = session.get('user');
const success = session.get('success');
const error = session.get('error');

return json<LoaderData>(
{
userId: userId,
success: success,
error: error,
},
{
headers: {
'Set-Cookie': await commitSession(session),
if (!userData) {
return json<LoaderData>(
{
userData: undefined,
success: success,
error: error,
},
},
);
{
headers: {
'Set-Cookie': await commitSession(session),
},
},
);
} else {
return json<LoaderData>(
{
userData: userData,
success: success,
error: error,
},
{
headers: {
'Set-Cookie': await commitSession(session),
},
},
);
}
};

export const action = async ({ request }: ActionFunctionArgs) => {
const session = await getSession(request.headers.get('Cookie'));
const userId = session.get('userId');
const userId = session.get('user');

const response = await logout({
headers: {
Expand All @@ -57,8 +73,7 @@ export const action = async ({ request }: ActionFunctionArgs) => {
});

if (response.status === 204) {
session.unset('userId');
session.unset('sessionToken');
session.unset('user');
session.flash('success', 'ログアウトに成功しました');

return redirect('/home', {
Expand All @@ -78,30 +93,25 @@ export const action = async ({ request }: ActionFunctionArgs) => {
};

const Home = () => {
const { userId, success, error } = useLoaderData<typeof loader>();
const { userData, success, error } = useLoaderData<typeof loader>();

const [user, setUser] = useAtom(userAtom);
const navigation = useNavigation();
const revalidator = useRevalidator();

useEffect(() => {
if (navigation.state === 'idle') {
if (userId) {
// CookieにユーザIDが存在する
if (!!userData) {
// Cookieにユーザ情報が保存されている
if (!user) {
// 状態変数にユーザ情報が保存されていない
// ユーザ情報を取得するAPIを呼び出す
getUser(userId).then((response) => {
if (response.status === 200) {
setUser(response.data);
}
});
// 状態変数にユーザ情報を保存する
setUser(userData);
}
} else {
setUser(undefined);
}
}
}, [userId]);
}, [userData]);

useEffect(() => {
if (success) {
Expand Down
5 changes: 2 additions & 3 deletions frontend/app/routes/login/route.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export const loader = async ({ request }: LoaderFunctionArgs) => {
const session = await getSession(request.headers.get('Cookie'));

// ログイン済みの場合
if (session.has('userId')) {
if (session.has('user')) {
// マイページへリダイレクト
return redirect('/home/mypage');
}
Expand Down Expand Up @@ -49,8 +49,7 @@ export const action = async ({ request }: ActionFunctionArgs) => {

// ログインに成功した場合
if (response.status === 200) {
session.set('userId', response.data.id.toString());
session.set('sessionToken', response.data.sessionToken!);
session.set('user', response.data);
session.flash('success', 'ログインに成功しました');

return redirect('/home/mypage', {
Expand Down
4 changes: 2 additions & 2 deletions frontend/app/services/session.server.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { createCookieSessionStorage } from '@remix-run/cloudflare';
import { User } from 'client/client.schemas';

interface SessionData {
userId: string;
sessionToken: string;
user: User;
}

interface SessionFlashData {
Expand Down

0 comments on commit f519027

Please sign in to comment.