Skip to content

Commit

Permalink
feat: 새로 고침 시 유저 정보 유지 (localStorage)
Browse files Browse the repository at this point in the history
  • Loading branch information
wildcatco committed Aug 21, 2023
1 parent 65c46aa commit c1c90eb
Show file tree
Hide file tree
Showing 14 changed files with 72 additions and 69 deletions.
26 changes: 17 additions & 9 deletions src/app/Routes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const CommentPage = lazy(() => import('@/pages/comment/CommentPage'));
const CommentReportPage = lazy(
() => import('@/pages/comment-report/CommentReportPage'),
);
const EditPage = lazy(() => import('@/pages/edit-post/EditPostPage'));
const EditPostPage = lazy(() => import('@/pages/edit-post/EditPostPage'));
const LoginPage = lazy(() => import('@/pages/login/LoginPage'));
const LoginOauthKakaoPage = lazy(
() => import('@/pages/login/LoginOauthKakaoPage'),
Expand All @@ -37,15 +37,20 @@ export default function Routes() {
return (
<Suspense fallback={null}>
<ReactRouterRoutes>
{/* 공개 페이지 */}
<Route path={'/'} element={<HomePage />} />
{/* 로그인한 유저만 접근 가능한 페이지 */}
<Route
element={
<ProtectedRoute isAllowed={!!user} redirectPath={'/login'} />
<ProtectedRoute
isAllowed={user?.joinStatus === 'activated'}
redirectPath={!user ? '/login' : '/register/term'}
/>
}
>
<Route path={'/feed/:id'} element={<FeedPage />} />
<Route path={'/feed/:id/:route'} element={<FeedPage />} />
<Route path={'/feed/:id/edit'} element={<EditPage />} />
<Route path={'/feed/:id/edit'} element={<EditPostPage />} />
<Route path={'/feed/:id/report'} element={<FeedReportPage />} />
<Route path={'/feed/:id/comment'} element={<CommentPage />} />
<Route path={'/write'} element={<WritePage />} />
Expand All @@ -55,27 +60,30 @@ export default function Routes() {
<Route path={'/comment/:id/report'} element={<CommentReportPage />} />
<Route path={'/unregister'} element={<UnregisterPage />} />
</Route>
{/* 로그인 안한 유저만 접근 가능한 페이지 */}
<Route
element={<ProtectedRoute isAllowed={!user} redirectPath={'/'} />}
>
<Route path={'/login'} element={<LoginPage />} />
</Route>
<Route
element={<ProtectedRoute isAllowed={!user} redirectPath={'/login'} />}
>
<Route
path={'/login/oauth/kakao'}
element={<LoginOauthKakaoPage />}
/>
</Route>
{/* 가입이 완료되지 않은 유저만 접근 가능한 페이지 */}
<Route
element={<ProtectedRoute isAllowed={!user?.job} redirectPath={'/'} />}
element={
<ProtectedRoute
isAllowed={user?.joinStatus === 'deactivated'}
redirectPath={'/'}
/>
}
>
<Route path={'/register/term'} element={<RegisterTermPage />} />
<Route
path={'/collect-information'}
element={<CollectInformationPage />}
/>
<Route path={'/register/term'} element={<RegisterTermPage />} />
</Route>
<Route path={'/*'} element={<Navigate to={'/'} />} />
</ReactRouterRoutes>
Expand Down
45 changes: 28 additions & 17 deletions src/features/user/queries/useUser.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,23 @@
import { useQuery } from '@tanstack/react-query';
import { AxiosError } from 'axios';
import { useMemo } from 'react';
import { useEffect, useMemo } from 'react';
import { axiosInstance } from '@/common/libs/axios';
import { User } from '@/features/user/types';
import { userLocalStorage } from '@/features/user/utils/user-local-storage';
import { GetUserResponse } from './dto/get-user';

async function getUser() {
const res = await axiosInstance.get<GetUserResponse>('/user');
return res.data;
}

export function useUser() {
const { data, isLoading } = useQuery({
const { data, isLoading, isError } = useQuery({
queryKey: ['user'],
queryFn: async () => {
try {
const res = await axiosInstance.get<GetUserResponse>('/user');
return res.data;
} catch (e) {
if (e instanceof AxiosError && e.response?.status === 401) {
return null;
} else {
throw e;
}
}
},
staleTime: 1000 * 60 * 60, // 1시간
queryFn: getUser,
refetchOnMount: false,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
initialData: userLocalStorage.getUser(),
});

const user: User | null = useMemo(
Expand All @@ -42,7 +39,7 @@ export function useUser() {
}
: null,
job: data.job,
worryCategories: data.userWorryCategories.map((category) => ({
worryCategories: data.userWorryCategories?.map((category) => ({
value: category.worryCategory.id,
label: category.worryCategory.label,
})),
Expand All @@ -52,6 +49,20 @@ export function useUser() {
[data],
);

useEffect(() => {
if (!user) {
userLocalStorage.removeUser();
} else {
userLocalStorage.saveUser(user);
}
}, [user]);

useEffect(() => {
if (isError) {
userLocalStorage.removeUser();
}
}, [isError]);

return {
user,
isLoggedIn: !!user,
Expand Down
16 changes: 16 additions & 0 deletions src/features/user/utils/user-local-storage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { User } from '../types';

const USER_LOCAL_STORAGE_KEY = 'GOCHAM-USER';

export const userLocalStorage = {
saveUser: (user: User) => {
localStorage.setItem(USER_LOCAL_STORAGE_KEY, JSON.stringify(user));
},
getUser: (): User | null => {
const user = localStorage.getItem(USER_LOCAL_STORAGE_KEY);
return user ? JSON.parse(user) : null;
},
removeUser: () => {
localStorage.removeItem(USER_LOCAL_STORAGE_KEY);
},
};
5 changes: 1 addition & 4 deletions src/pages/comment-report/CommentReportPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,10 @@ import { TopAppBar } from '@/common/components/layout';
import { Button } from '@/common/components/ui/buttons';
import { LoadingSpinner } from '@/common/components/ui/loading';
import { REPORT_COMMENT_REASON_OPTIONS } from '@/common/constants/options';
import { withAuth } from '@/features/auth/components/withAuth/withAuth';
import { useReportComment } from '@/features/report/queries';
import { useUser } from '@/features/user/queries/useUser';

function CommentReportPage() {
export default function CommentReportPage() {
const { id } = useParams();
const { user } = useUser();
const [selectedReasonId, setSelectedReasonId] = useState<number>();
Expand Down Expand Up @@ -120,5 +119,3 @@ function CommentReportPage() {
</div>
);
}

export default withAuth(CommentReportPage, { block: 'unauthenticated' });
5 changes: 1 addition & 4 deletions src/pages/edit-post/EditPostPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,12 @@ import { useNavigate, useParams } from 'react-router-dom';
import { TopAppBar } from '@/common/components/layout';
import { LoadingSpinner } from '@/common/components/ui/loading';
import { Popup } from '@/common/components/ui/modal';
import { withAuth } from '@/features/auth/components/withAuth/withAuth';
import { PostForm } from '@/features/posts/components/post-form/PostForm';
import { useEditPost, useGetPost } from '@/features/posts/queries';
import { PostFormData } from '@/features/posts/types/post-form';
import { useUser } from '@/features/user/queries/useUser';

function EditPostPage() {
export default function EditPostPage() {
const queryClient = useQueryClient();
const { id } = useParams();
const [modalOpen, setModalOpen] = useState(false);
Expand Down Expand Up @@ -146,5 +145,3 @@ function EditPostPage() {
</>
);
}

export default withAuth(EditPostPage, { block: 'unauthenticated' });
5 changes: 1 addition & 4 deletions src/pages/feed-report/FeedReportPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,11 @@ import { TopAppBar } from '@/common/components/layout';
import { Button } from '@/common/components/ui/buttons';
import { LoadingSpinner } from '@/common/components/ui/loading';
import { REPORT_FEED_REASON_OPTIONS } from '@/common/constants/options';
import { withAuth } from '@/features/auth/components/withAuth/withAuth';
import { useGetPost } from '@/features/posts/queries';
import { useReportPost } from '@/features/report/queries';
import { useUser } from '@/features/user/queries/useUser';

function FeedPage() {
export default function FeedPage() {
const { id } = useParams();
const { user } = useUser();
const { data: post } = useGetPost(Number(id));
Expand Down Expand Up @@ -99,5 +98,3 @@ function FeedPage() {
</div>
);
}

export default withAuth(FeedPage, { block: 'unauthenticated' });
5 changes: 1 addition & 4 deletions src/pages/feed/FeedPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,13 @@ import { Suspense, useEffect } from 'react';
import { useParams } from 'react-router-dom';
import { PageWrapper, TopAppBar } from '@/common/components/layout';
import { POST_TYPE } from '@/common/constants/post-type';
import { withAuth } from '@/features/auth/components/withAuth/withAuth';
import {
PostDetailList,
PostDetailListSkeleton,
} from '@/features/posts/components/post-detail';
import { selectedVoteOptionIdAtom } from '@/features/vote/states/selected-vote-option';

function FeedPage() {
export default function FeedPage() {
const params = useParams();
const postType = (params.route as POST_TYPE) || POST_TYPE.ALL;
const setSelectedVoteOptionId = useSetAtom(selectedVoteOptionIdAtom);
Expand Down Expand Up @@ -39,5 +38,3 @@ function FeedPage() {
</PageWrapper>
);
}

export default withAuth(FeedPage, { block: 'unauthenticated' });
5 changes: 1 addition & 4 deletions src/pages/login/LoginPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@ import { useNavigate } from 'react-router-dom';
import Kakao from '@/common/assets/images/login/kakao.svg';
import LoginWrapper from '@/common/assets/images/login/loginWrapper.svg';
import BackIcon from '@/common/components/icons/BackIcon';
import { withAuth } from '@/features/auth/components/withAuth/withAuth';

function LoginPage() {
export default function LoginPage() {
const navigate = useNavigate();

if (!window.Kakao.isInitialized()) {
Expand Down Expand Up @@ -76,5 +75,3 @@ function LoginPage() {
</div>
);
}

export default withAuth(LoginPage, { block: 'activated' });
5 changes: 1 addition & 4 deletions src/pages/register/CollectInformationPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,14 @@ import { useAtom } from 'jotai';
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import BackIcon from '@/common/components/icons/BackIcon';
import { withAuth } from '@/features/auth/components/withAuth/withAuth';
import { useAcceptTerms } from '@/features/auth/queries';
import { registerDataAtom } from '@/features/register/states/register-data';
import CollectNicknameAgeGender from '@/features/user/components/CollectNicknameAgeGender/CollectNicknameAgeGender';
import CollectRegionJobCategory from '@/features/user/components/CollectRegionJobCategory/CollectRegionJobCategory';
import { useEditProfile } from '@/features/user/queries/useEditProfile';
import { useUser } from '@/features/user/queries/useUser';

function CollectInformationPage() {
export default function CollectInformationPage() {
const navigate = useNavigate();
const [page, setPage] = useState(1);
const [registerData, setRegisterData] = useAtom(registerDataAtom);
Expand Down Expand Up @@ -124,5 +123,3 @@ function CollectInformationPage() {
</div>
);
}

export default withAuth(CollectInformationPage, { block: 'activated' });
5 changes: 1 addition & 4 deletions src/pages/register/RegisterTermPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,10 @@ import { useAtom } from 'jotai';
import { useNavigate } from 'react-router-dom';
import BackIcon from '@/common/components/icons/BackIcon';
import { Button } from '@/common/components/ui/buttons';
import { withAuth } from '@/features/auth/components/withAuth/withAuth';
import { registerDataAtom } from '@/features/register/states/register-data';
import { TermCheckbox } from '@/pages/register/components/TermCheckbox';

function RegisterTermPage() {
export default function RegisterTermPage() {
const navigate = useNavigate();
const [registerData, setRegisterData] = useAtom(registerDataAtom);
const { accept } = registerData;
Expand Down Expand Up @@ -88,5 +87,3 @@ function RegisterTermPage() {
</div>
);
}

export default withAuth(RegisterTermPage, { block: 'activated' });
5 changes: 1 addition & 4 deletions src/pages/settings/SettingsPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,8 @@ import { useNavigate } from 'react-router-dom';
import BackIcon from '@/common/components/icons/BackIcon';
import { TopAppBar } from '@/common/components/layout';
import { Popup } from '@/common/components/ui/modal';
import { withAuth } from '@/features/auth/components/withAuth/withAuth';

function SettingsPage() {
export default function SettingsPage() {
const navigate = useNavigate();
const queryClient = useQueryClient();
const [logoutModalOpen, setLogoutModalOpen] = useState(false);
Expand Down Expand Up @@ -87,5 +86,3 @@ function SettingsPage() {
</div>
);
}

export default withAuth(SettingsPage, { block: 'unauthenticated' });
4 changes: 1 addition & 3 deletions src/pages/unregister/UnregisterPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,11 @@ import { useNavigate } from 'react-router-dom';
import { TopAppBar } from '@/common/components/layout';
import { Button } from '@/common/components/ui/buttons';
import { Popup } from '@/common/components/ui/modal';
import { withAuth } from '@/features/auth/components/withAuth/withAuth';
import { PostVoteInput } from '@/features/posts/components/post-form';
import { useUnregister } from '@/features/user/queries/useUnregister';
import { useUser } from '@/features/user/queries/useUser';

function UnregisterPage() {
export default function UnregisterPage() {
const { user } = useUser();
const [reason, setReason] = useState('');
const [modalOpen, setModalOpen] = useState(false);
Expand Down Expand Up @@ -112,4 +111,3 @@ function UnregisterPage() {
</div>
);
}
export default withAuth(UnregisterPage, { block: 'unauthenticated' });
5 changes: 1 addition & 4 deletions src/pages/user/UserPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,13 @@ import { usePullToRefresh } from '@/common/hooks/usePullToRefresh';
import { useScrollRestoration } from '@/common/hooks/useScrollRestoration';
import { useScrollToTop } from '@/common/hooks/useScrollToTop';
import { assignMultipleRefs } from '@/common/utils/dom/assign-multiple-refs';
import { withAuth } from '@/features/auth/components/withAuth/withAuth';
import { PostCardList } from '@/features/posts/components/post-card/PostCardList';
import { PostCardListSkeleton } from '@/features/posts/components/post-card/PostCardListSkeleton';
import { selectedPostTypeAtom } from '@/features/posts/states/selected-post-type';
import { PostTypeTabList } from '@/features/user/components/PostTypeTabList';
import { UserPageHeader } from '@/pages/user/components/UserPageHeader';

function UserPage() {
export default function UserPage() {
const queryClient = useQueryClient();
const [selectedPostType, setSelectedPostType] = useAtom(selectedPostTypeAtom);
const { ref: scrollToTopRef, scrollToTop } = useScrollToTop<HTMLDivElement>();
Expand Down Expand Up @@ -74,5 +73,3 @@ function UserPage() {
</PageWrapper>
);
}

export default withAuth(UserPage, { block: 'unauthenticated' });
5 changes: 1 addition & 4 deletions src/pages/write/WritePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,14 @@ import { TopAppBar } from '@/common/components/layout';
import { Popup } from '@/common/components/ui/modal';
import { scrollRestorationAtom } from '@/common/states/scroll-restoration';
import getFutureDateTime from '@/common/utils/getFutureDateTime';
import { withAuth } from '@/features/auth/components/withAuth/withAuth';
import { PostForm } from '@/features/posts/components/post-form/PostForm';
import { useAddPost } from '@/features/posts/queries';
import { PostFormData } from '@/features/posts/types/post-form';
import { useUser } from '@/features/user/queries';
import { PostUploadSuccess } from '@/pages/write/components/PostUploadSuccess';
import { PostUploading } from '@/pages/write/components/PostUploading';

function WritePage() {
export default function WritePage() {
const [modalOpen, setModalOpen] = useState(false);
const navigate = useNavigate();
const { mutate: addPost, isLoading, isSuccess, data } = useAddPost();
Expand Down Expand Up @@ -121,5 +120,3 @@ function WritePage() {
</>
);
}

export default withAuth(WritePage, { block: 'unauthenticated' });

0 comments on commit c1c90eb

Please sign in to comment.