Skip to content

Commit

Permalink
메인페이지가-최신화되지않는-오류-해결 (#32)
Browse files Browse the repository at this point in the history
* Refactor : 서버 인터페이스 수정

* New : 토큰을 불러오는 훅 추가

* Refactor : 서버 인터페이스 수정

* Refactor : 기본 스테일타임 추가

* Fix : 메인페이지가 최신화되지않는 오류 수정

* Refactor : Production Env파일 추가에 따른 .gitignore 변경
  • Loading branch information
jobkaeHenry authored Nov 12, 2023
1 parent f9b4ac1 commit 1ce00e6
Show file tree
Hide file tree
Showing 12 changed files with 69 additions and 15 deletions.
1 change: 1 addition & 0 deletions client/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,5 @@ public/sw.js
public/workbox-*.js

# Env
.env.*
.env
3 changes: 2 additions & 1 deletion client/src/app/(protectedRoute)/new-post/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import axios from "@/libs/axios";
import HOME from "@/const/clientPath";
import CameraIcon from "@/assets/icons/CameraIcon.svg";
import PinIcon from "@/assets/icons/PinIcon.svg";
import getTokenFromLocalStorage from "@/utils/getTokenFromLocalStorage";

export default function NewpostPage() {
const [formValue, setFormValue] = useState({
Expand All @@ -35,7 +36,7 @@ export default function NewpostPage() {
setFormValue((prev) => ({ ...prev, [target.name]: target.value }));
};

const token = localStorage.getItem("accessToken");
const token = getTokenFromLocalStorage();

const router = useRouter();

Expand Down
9 changes: 8 additions & 1 deletion client/src/app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,16 @@
import PostCardList from "@/components/post/PostCardList";
import { getPostListQueryFn } from "@/queries/post/useGetPostListInfiniteQuery";
import { Container, Paper } from "@mui/material";
import { cookies } from "next/headers";

export default async function Home() {
const initialData = await getPostListQueryFn({ page: 0, size: 10 });
const accessToken = cookies().get("accessToken")?.value;

const initialData = await getPostListQueryFn({
page: 0,
size: 10,
headers: { Authorization: accessToken },
});

return (
<Container sx={{ px: { xs: 0, sm: 4 } }} maxWidth={"lg"}>
Expand Down
3 changes: 3 additions & 0 deletions client/src/app/search/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,17 @@
import SearchArea from "@/components/search/SearchArea";
import { getPostListQueryFn } from "@/queries/post/useGetPostListInfiniteQuery";
import { Container } from "@mui/material";
import { cookies } from "next/headers";

const SearchPage = async ({
searchParams,
}: {
searchParams?: { [key: string]: string | undefined };
}) => {
const accessToken = cookies().get("accessToken")?.value;
const initialData = await getPostListQueryFn({
searchKeyword: searchParams?.keyword,
headers: { Authorization: accessToken },
});
return (
<Container sx={{ px: { xs: 0, sm: 4 } }} maxWidth={"lg"}>
Expand Down
7 changes: 4 additions & 3 deletions client/src/components/post/PostCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,9 @@ const PostCard = ({
alcoholName,
alcoholType,
commentCount,
likedByme,
likedByMe,
}: PostInterface) => {

const openPostDetailPage = useOpenPostDetailPage();
const hasImage = useMemo(() => postAttachUrls.length !== 0, [postAttachUrls]);
const { mutate: likeHandler } = useLikePostMutation();
Expand Down Expand Up @@ -132,10 +133,10 @@ const PostCard = ({
data-testid="likeBtn"
aria-label="like"
onClick={() => {
likedByme ? unLikeHandler(postNo) : likeHandler(postNo);
likedByMe ? unLikeHandler(postNo) : likeHandler(postNo);
}}
>
<Box style={{ color: likedByme ? "primary.main" : "#d9d9d9" }}>
<Box sx={{ color: likedByMe ? "primary.main" : "#d9d9d9" }}>
<LikeIcon />
</Box>
<Typography variant="label">{likeCount ?? 0}</Typography>
Expand Down
9 changes: 7 additions & 2 deletions client/src/components/post/PostCardList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,25 +10,30 @@ import { Box, CircularProgress } from "@mui/material";
import { useMemo } from "react";
import Image from "next/image";
import NoResult from "@/assets/images/noResult.png";
import getTokenFromLocalStorage from "@/utils/getTokenFromLocalStorage";

function PostCardList(props: UseGetPostListQueryInterface) {
const { data, fetchNextPage, isFetchingNextPage, hasNextPage } =
useGetPostListInfiniteQuery({
...props,
headers: { Authorization: getTokenFromLocalStorage() },
});
const { ref, inView } = useInView();

useEffect(() => {
if (hasNextPage && inView) fetchNextPage();
}, [inView, hasNextPage]);

const hasResult = useMemo(() => data.pages[0].list.length > 0, [data]);
const hasResult = useMemo(
() => data && data.pages[0].list.length > 0,
[data]
);

return (
<div>
{hasResult ? (
// 검색결과가 있을시
data.pages.map((page) =>
data?.pages.map((page) =>
page.list.map((post) => <PostCard {...post} key={post.postNo} />)
)
) : (
Expand Down
11 changes: 10 additions & 1 deletion client/src/components/queryClient/CustomQueryClientProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,16 @@ export default function CustomQueryClientProvider({
}: {
children?: ReactNode;
}) {
const [queryClient] = useState(() => new QueryClient());
const [queryClient] = useState(
() =>
new QueryClient({
defaultOptions: {
queries: {
staleTime: 60 * 1000,
},
},
})
);

return (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
Expand Down
23 changes: 19 additions & 4 deletions client/src/queries/post/useGetPostListInfiniteQuery.tsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,32 @@
import { useSuspenseInfiniteQuery } from "@tanstack/react-query";
import { useInfiniteQuery } from "@tanstack/react-query";
import axios from "@/libs/axios";
import { PostInterface } from "@/types/post/PostInterface";
import { AxiosRequestConfig } from "axios";
import getTokenFromLocalStorage from "@/utils/getTokenFromLocalStorage";

export interface UseGetPostListQueryInterface extends GetPostListOptions {
initialData?: AugmentedGetPostListResponse;
headers?: AxiosRequestConfig["headers"];
}

export const useGetPostListInfiniteQuery = ({
initialData,
size,
searchKeyword,
headers,
}: UseGetPostListQueryInterface) => {
return useSuspenseInfiniteQuery({
return useInfiniteQuery({
queryKey: getPostListInfiniteQueryKey.byKeyword(searchKeyword),

queryFn: async ({ pageParam = 0 }) =>
await getPostListQueryFn({ page: pageParam, size, searchKeyword }),
await getPostListQueryFn({
page: pageParam,
size,
searchKeyword,
headers: headers?.Authorization
? headers
: { Authorization: getTokenFromLocalStorage() },
}),

getNextPageParam: ({
currentPage,
Expand Down Expand Up @@ -58,10 +69,14 @@ export const getPostListQueryFn = async ({
page = 0,
size = 10,
searchKeyword,
}: GetPostListOptions): Promise<AugmentedGetPostListResponse> => {
headers,
}: GetPostListOptions & {
headers?: AxiosRequestConfig<any>["headers"];
}): Promise<AugmentedGetPostListResponse> => {
const { data } = await axios.get<GetPostListResponse>("/posts", {
baseURL: process.env.NEXT_PUBLIC_BASE_URL,
params: { page, size, searchKeyword },
headers,
});
return {
...data,
Expand Down
3 changes: 2 additions & 1 deletion client/src/queries/post/useLikePostMutation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import axios from "@/libs/axios";
import { PostInterface } from "@/types/post/PostInterface";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { getPostListInfiniteQueryKey } from "./useGetPostListInfiniteQuery";
import getTokenFromLocalStorage from "@/utils/getTokenFromLocalStorage";
/**
* 좋아요를 수행하고, 게시글을 invalidation 하는 쿼리
* @returns
Expand All @@ -24,7 +25,7 @@ const useLikePostMutation = () => {
* @returns
*/
export const useLikePostMutationFn = async (id: PostInterface["postNo"]) => {
const token = localStorage.getItem("accessToken");
const token = getTokenFromLocalStorage();
// FIXME 리터럴제거
const { data } = await axios.post(`/posts/like/${id}`, null, {
headers: { Authorization: token },
Expand Down
3 changes: 2 additions & 1 deletion client/src/queries/post/useUnLikePostMutation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import axios from "@/libs/axios";
import { PostInterface } from "@/types/post/PostInterface";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { getPostListInfiniteQueryKey } from "./useGetPostListInfiniteQuery";
import getTokenFromLocalStorage from "@/utils/getTokenFromLocalStorage";
/**
* 좋아요를 취소하고, 게시글을 invalidation 하는 쿼리
* @returns
Expand All @@ -24,7 +25,7 @@ const useLikePostMutation = () => {
* @returns
*/
export const useLikePostMutationFn = async (id: PostInterface["postNo"]) => {
const token = localStorage.getItem("accessToken");
const token = getTokenFromLocalStorage();
// FIXME 리터럴제거
const { data } = await axios.post(`/posts/like-cancel/${id}`, null, {
headers: { Authorization: token },
Expand Down
2 changes: 1 addition & 1 deletion client/src/types/post/PostInterface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ export interface PostInterface {
/**
* 내가 좋아요를 눌렀는지 여부
*/
likedByme: boolean;
likedByMe: boolean;
}

type QuoteInfoType = {
Expand Down
10 changes: 10 additions & 0 deletions client/src/utils/getTokenFromLocalStorage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/**
* 로컬스토리지에서 AccessToken을 불러오는 유틸함수
* 클라이언트 단에서만 동작
*/
export default function getTokenFromLocalStorage() {
if (typeof window === "undefined") {
return;
}
return localStorage.getItem("accessToken");
}

0 comments on commit 1ce00e6

Please sign in to comment.