Skip to content

Commit

Permalink
chore : fetch api -> axios로 마저 변경
Browse files Browse the repository at this point in the history
  • Loading branch information
guen9310 committed Jan 20, 2024
1 parent 3bffa4a commit 5c7719d
Show file tree
Hide file tree
Showing 12 changed files with 62 additions and 53 deletions.
16 changes: 8 additions & 8 deletions hooks/useTokenFetch.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
import { useState, useEffect, useCallback } from "react";
import axios, { CancelTokenSource } from "axios";

function useTokenFetch<T>(url: string): { data: T | null; loading: boolean } {
const [fetchData, setFetchData] = useState<T | null>(null);
const [loading, setLoading] = useState<boolean>(true);

const fetching = useCallback(
async (token: string, controller: AbortController) => {
async (token: string, cancelToken: CancelTokenSource) => {
setLoading(true);
try {
const response = await fetch(url, {
const response = await axios.get(url, {
headers: {
Authorization: `Bearer ${token}`,
},
signal: controller.signal,
cancelToken: cancelToken.token,
});

const data = (await response.json()) as T;
setFetchData(data);
setFetchData(response.data);
} catch (error) {
console.error(error);
setFetchData(null);
Expand All @@ -29,16 +29,16 @@ function useTokenFetch<T>(url: string): { data: T | null; loading: boolean } {

useEffect(() => {
const token = localStorage.getItem("accessToken");
const controller = new AbortController();
const cancelToken = axios.CancelToken.source();

if (token) {
fetching(token, controller);
fetching(token, cancelToken);
} else {
setLoading(false);
}

return () => {
controller.abort();
cancelToken.cancel();
};
}, [fetching]);

Expand Down
25 changes: 11 additions & 14 deletions layouts/auth/Section/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import Cta from "@/components/common/Cta";
import { authMapping } from "@/lib/mapping/auth";
import * as S from "./styled";
import { AuthType } from "@/types/global.type";
import { instance } from "@/pages/api/instance";

interface AuthSectionProps {
type: AuthType;
Expand All @@ -31,20 +32,16 @@ function AuthSection({ type, children }: AuthSectionProps) {
const serviceTypeUrl = userServices[type];

const onSubmit = async (data: AuthForm) => {
await fetch(serviceTypeUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ ...data }),
})
.then((res) => res.json())
.then((response: Response) => {
const { accessToken } = response.data;
localStorage.setItem("accessToken", accessToken);
})
.then(() => router.push("/folder"))
.catch((e) => console.error(e));
try {
const response = await instance.post(serviceTypeUrl, data);
const {
data: { accessToken },
} = response.data;
localStorage.setItem("accessToken", accessToken);
router.push("/folder");
} catch (error) {
console.error(error);
}
};

return (
Expand Down
3 changes: 2 additions & 1 deletion pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@ export default function App({ Component, pageProps }: AppProps) {
useEffect(() => {
const getAccessToken = localStorage.getItem("accessToken");
const protectedPaths = ["/shared", "/folder"];
const isProtectedPath = protectedPaths.some((path) => router.pathname.startsWith(path));
const isAuthPath = router.pathname.startsWith("/auth");

if (protectedPaths.includes(router.pathname) && !getAccessToken) {
if (isProtectedPath && !getAccessToken) {
router.push("/");
} else if (isAuthPath && getAccessToken) {
router.push("/folder");
Expand Down
4 changes: 2 additions & 2 deletions pages/api/folder/[id].ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { NextApiRequest, NextApiResponse } from "next";
import { folderServices } from "../address";
import { apiClient, setAuthToken } from "../instance";
import { instance, setAuthToken } from "../instance";

async function handler(req: NextApiRequest, res: NextApiResponse) {
const {
Expand All @@ -12,7 +12,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
const token = req.headers.authorization;
setAuthToken(token);
try {
const { data: response } = await apiClient.get(folderServices.getSelectedFolder(folderId));
const { data: response } = await instance.get(folderServices.getSelectedFolder(folderId));
return res.json({
ok: true,
folders: response.data,
Expand Down
4 changes: 2 additions & 2 deletions pages/api/folder/index.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { NextApiRequest, NextApiResponse } from "next";
import { apiClient, setAuthToken } from "../instance";
import { instance, setAuthToken } from "../instance";
import { folderServices } from "../address";

async function handler(req: NextApiRequest, res: NextApiResponse) {
const token = req.headers.authorization;
setAuthToken(token);
try {
const { data: response } = await apiClient.get(folderServices.getFolder);
const { data: response } = await instance.get(folderServices.getFolder);
const { folder } = response.data;
return res.json({
ok: true,
Expand Down
14 changes: 6 additions & 8 deletions pages/api/instance.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,17 @@
import { END_POINT } from "@/lib/constents";
import axios from "axios";
import { END_POINT } from "@/lib/constents";

const apiClient = axios.create({
const instance = axios.create({
baseURL: END_POINT,
headers: {
"Content-Type": "application/json",
},
});

// next.js node 서버에서 사용될 토큰
const setAuthToken = (token: string | undefined) => {
if (token) {
apiClient.defaults.headers.common["Authorization"] = `${token}`;
instance.defaults.headers.common["Authorization"] = `${token}`;
} else {
delete apiClient.defaults.headers.common["Authorization"];
delete instance.defaults.headers.common["Authorization"];
}
};

export { apiClient, setAuthToken };
export { instance, setAuthToken };
4 changes: 2 additions & 2 deletions pages/api/links/[id].ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { NextApiRequest, NextApiResponse } from "next";
import { folderServices } from "../address";
import { LinkData } from "@/types/contents.type";
import { Links } from "@/types/global.type";
import { apiClient, setAuthToken } from "../instance";
import { instance, setAuthToken } from "../instance";

async function handler(req: NextApiRequest, res: NextApiResponse) {
const {
Expand All @@ -14,7 +14,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
const token = req.headers.authorization;
setAuthToken(token);
try {
const { data: response } = await apiClient.get(folderServices.getSelectedFolderLinks(folderId));
const { data: response } = await instance.get(folderServices.getSelectedFolderLinks(folderId));
const { folder } = response.data;

const convertLinks: Links[] = folder.map((link: LinkData) => ({
Expand Down
4 changes: 2 additions & 2 deletions pages/api/links/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ import { NextApiRequest, NextApiResponse } from "next";
import { folderServices } from "../address";
import { LinkData } from "@/types/contents.type";
import { Links } from "@/types/global.type";
import { apiClient, setAuthToken } from "../instance";
import { instance, setAuthToken } from "../instance";

async function handler(req: NextApiRequest, res: NextApiResponse) {
const token = req.headers.authorization;
setAuthToken(token);
try {
const { data: response } = await apiClient.get(folderServices.getLinks);
const { data: response } = await instance.get(folderServices.getLinks);
const { folder } = response.data;

const convertLinks: Links[] = folder.map((link: LinkData) => ({
Expand Down
4 changes: 2 additions & 2 deletions pages/api/users/index.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { NextApiRequest, NextApiResponse } from "next";
import { userServices } from "../address";
import { apiClient, setAuthToken } from "../instance";
import { instance, setAuthToken } from "../instance";

async function handler(req: NextApiRequest, res: NextApiResponse) {
const token = req.headers.authorization;
setAuthToken(token);
try {
const { data: users } = await apiClient.get(userServices.getProfile);
const { data: users } = await instance.get(userServices.getProfile);
const user = users.data[0];

return res.json({
Expand Down
20 changes: 10 additions & 10 deletions pages/auth/signup.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { FormProvider, useForm } from "react-hook-form";
import AuthLayout from "@/layouts/auth";
import InputField from "@/components/common/InputField";
import { userServices } from "@/pages/api/address";
import { instance } from "../api/instance";
import axios from "axios";

interface AuthForm {
email: string;
Expand All @@ -14,17 +16,15 @@ const SignUpPage = () => {
const methods = useForm<AuthForm>();

const checkedEmail = async (email: string) => {
const response = await fetch(userServices.checkedEmail, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ email }),
});
if (response?.status === 409) {
return "이미 사용중인 이메일입니다.";
try {
await instance.post(userServices.checkedEmail, { email });
return true;
} catch (error) {
if (axios.isAxiosError(error)) {
return "이미 사용중인 이메일입니다.";
}
throw error;
}
return true;
};

return (
Expand Down
13 changes: 13 additions & 0 deletions pages/folder/[[...id]].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,16 @@ function FolderPage() {
}

export default FolderPage;

export async function getStaticPaths() {
return {
paths: [],
fallback: true,
};
}

export async function getStaticProps() {
return {
props: {},
};
}
4 changes: 2 additions & 2 deletions pages/shared/[id].tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import React, { useEffect, useState } from "react";
import Head from "next/head";
import { useRouter } from "next/router";
import SharedLayout from "@/layouts/share";
import { FolderData, LinksResponse } from "@/types/contents.type";
import { useRouter } from "next/router";
import useTokenFetch from "@/hooks/useTokenFetch";
import { API_PATH } from "@/lib/constents";
import { UserResponse } from "@/types/user.type";
Expand All @@ -22,7 +22,7 @@ function SharedPage({ folders }: { folders: FolderData }) {
const name = folders.name;

useEffect(() => {
if (!folderLoading && !linksLoading) {
if (!folderLoading && linksLoading) {
setIsLoading(false);
} else {
setIsLoading(true);
Expand Down

0 comments on commit 5c7719d

Please sign in to comment.