Skip to content

Commit

Permalink
Merge pull request #106 from hufs-sports-live/fix/localstorage
Browse files Browse the repository at this point in the history
[FIX]: 빌드 에러 픽스
  • Loading branch information
HiimKwak authored Nov 28, 2023
2 parents d36514b + 09fbb6d commit 8339bf2
Show file tree
Hide file tree
Showing 9 changed files with 260 additions and 30 deletions.
4 changes: 3 additions & 1 deletion src/api/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import axios from 'axios';

import LocalStorage from '@/utils/LocalStorage';

const instance = axios.create({
baseURL: process.env.NEXT_PUBLIC_API_BASE_URL,
headers: {
Expand All @@ -16,7 +18,7 @@ export const adminInstance = axios.create({
});

adminInstance.interceptors.request.use(config => {
config.headers.Authorization = `Bearer ${localStorage.getItem('token')}`;
config.headers.Authorization = `Bearer ${LocalStorage.getItem('token')}`;

return config;
});
Expand Down
11 changes: 9 additions & 2 deletions src/app/admin/league/page.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
'use client';

import dynamic from 'next/dynamic';
import Link from 'next/link';
import { Suspense } from 'react';

import LeagueList from '@/components/admin/league/LeagueList';
import Button from '@/components/common/Button';
import LeagueListFetcher from '@/queries/admin/useLeagueList/Fetcher';

const LeagueListFetcher = dynamic(
() => import('@/queries/admin/useLeagueList/Fetcher'),
{ ssr: false },
);
const LeagueList = dynamic(
() => import('@/components/admin/league/LeagueList'),
);

export default function LeaguePage() {
return (
Expand Down
10 changes: 3 additions & 7 deletions src/app/admin/register/[leagueId]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,19 @@

import { Suspense } from 'react';

import RegisterLeague from '@/components/admin/register/League';
import EditLeague from '@/components/admin/register/League/edit';
import LeagueRegisterFetcher from '@/queries/admin/useLeagueRegister/Fetcher';
import useSportsListByLeagueId from '@/queries/useSportsListByLeagueId/query';

export default function EditLeague({
params,
}: {
params: { leagueId: string };
}) {
export default function Edit({ params }: { params: { leagueId: string } }) {
const { leagueId } = params;
const { sportsList: leagueSportsData } = useSportsListByLeagueId(leagueId);
return (
<div className="space-y-8 py-8">
<Suspense fallback={<div>리그 정보 로딩중...</div>}>
<LeagueRegisterFetcher>
{data => (
<RegisterLeague
<EditLeague
data={{ ...data, leagueSportsData }}
leagueId={Number(leagueId)}
/>
Expand Down
2 changes: 1 addition & 1 deletion src/app/admin/register/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import { Suspense } from 'react';

import RegisterWrapper from '@/components/admin/register/context/RegisterWrapper';
import RegisterLeague from '@/components/admin/register/League';
import RegisterLeague from '@/components/admin/register/League/';
import RegisterTeam from '@/components/admin/register/Team';
import { useFunnel } from '@/hooks/useFunnel';
import LeagueRegisterFetcher from '@/queries/admin/useLeagueRegister/Fetcher';
Expand Down
213 changes: 213 additions & 0 deletions src/components/admin/register/League/edit/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,213 @@
'use client';

import { useRouter } from 'next/navigation';
import { ChangeEvent, FormEvent, useEffect, useState } from 'react';

import Button from '@/components/common/Button';
import CheckboxItem from '@/components/common/Checkbox/Item';
import Input from '@/components/common/Input/Input';
import useValidate from '@/hooks/useValidate';
import {
usePostLeagueMutation,
usePutLeagueMutation,
} from '@/queries/admin/useLeagueRegister/query';
import {
LeagueDataType,
LeagueRegisterDataType,
SportsDataType,
} from '@/types/admin/league';
import { SportsType } from '@/types/league';
import { updateSet } from '@/utils/set';
import { parseTimeString } from '@/utils/time';

export default function EditLeague({
data,
leagueId,
onNext,
}: {
data: LeagueRegisterDataType & { leagueSportsData: SportsType[] };
leagueId?: number;
onNext?: () => void;
}) {
const [newLeagueData, setNewLeagueData] = useState<LeagueDataType>(
{} as LeagueDataType,
);
const [newSportsData, setNewSportsData] = useState<Set<number>>(new Set());

const { leagueData, leagueSportsData, sportsListData } = data;
const currentLeague = leagueData.find(e => e.leagueId === Number(leagueId));

const router = useRouter();

const { mutate: postLeague } = usePostLeagueMutation();
const { mutate: putLeague } = usePutLeagueMutation();

useEffect(() => {
if (currentLeague) {
const parseDate = (dateString: string) => dateString.split('T')[0];

setNewLeagueData({
name: currentLeague.name,
startAt: parseDate(currentLeague.startAt),
endAt: parseDate(currentLeague.endAt),
});
}
if (leagueSportsData) {
const reducedSportsData = leagueSportsData.reduce(
(acc, cur) => [...acc, cur.sportId],
[] as SportsDataType,
);

setNewSportsData(new Set(reducedSportsData));
}
}, []);

const { month, date } = parseTimeString(new Date().toString());

const isDateError =
new Date(newLeagueData.endAt) < new Date(newLeagueData.startAt);
const { isError: isStartAtEmpty } = useValidate(
newLeagueData.startAt,
dateValue => !dateValue,
);
const { isError: isEndAtEmpty } = useValidate(
newLeagueData.endAt,
dateValue => !dateValue,
);
const { isError: isNameEmpty } = useValidate(
newLeagueData.name,
nameValue => String(nameValue).length < 1,
);
const { isError: isSportsEmpty } = useValidate(
Array.from(newSportsData).length,
length => length === 0,
);
const isAnyInvalid =
isNameEmpty ||
isDateError ||
isSportsEmpty ||
isStartAtEmpty ||
isEndAtEmpty;

const updateCheckbox = (id: number) => {
setNewSportsData(prevSet => updateSet<number>(prevSet, id));
};

const handleInput = (
e: ChangeEvent<HTMLInputElement | HTMLSelectElement>,
) => {
const { name, value } = e.target;

setNewLeagueData(prev => ({ ...prev, [name]: value }));
};

const onSubmit = (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();

const payload = {
leagueData: newLeagueData,
sportData: Array.from(newSportsData),
};

if (leagueId) {
putLeague({
leagueId,
...payload,
});
} else {
postLeague(payload);
}

if (onNext) {
onNext();
} else {
router.push('/admin/league/');
}
};

return (
<div className="space-y-8">
<div className="text-2xl font-medium">
{currentLeague ? '리그 수정' : '새 리그 등록'}
</div>
<form className="flex flex-col space-y-4" onSubmit={onSubmit}>
<label>
<div className="flex items-center justify-between">
<span>리그 이름</span>
{isNameEmpty && (
<span className="text-sm text-red-400">필수 항목입니다.</span>
)}
</div>
<Input
name="name"
type="text"
value={newLeagueData.name}
onChange={handleInput}
required
/>
</label>
<label>
<div className="flex items-center justify-between">
<span>리그 시작/종료일</span>
{isStartAtEmpty || isEndAtEmpty ? (
<span className="text-sm text-red-400">날짜를 선택해주세요.</span>
) : (
isDateError && (
<span className="text-sm text-red-400">
종료일은 시작일보다 이후로 설정해주세요!
</span>
)
)}
</div>
<Input
name="startAt"
type="date"
value={newLeagueData.startAt}
onChange={handleInput}
min={`2023-${month}-${date.toString().padStart(2, '0')}`}
max={'2023-12-3'}
required
/>
<Input
name="endAt"
type="date"
value={newLeagueData.endAt}
onChange={handleInput}
min={`2023-${month}-${date.toString().padStart(2, '0')}`}
max={'2023-12-3'}
required
/>
</label>
<label>
<div className="flex items-center justify-between">
<span>리그 종목</span>
{isSportsEmpty && (
<span className="text-sm text-red-400">
적어도 한 종목은 선택해주세요.
</span>
)}
</div>
{sportsListData.map(({ name, sportId }) => (
<CheckboxItem
key={sportId}
id={String(sportId)}
name="sportData"
value={sportId}
checked={newSportsData.has(+sportId)}
onChange={() => updateCheckbox(+sportId)}
>
{name}
</CheckboxItem>
))}
</label>
<Button
className="w-full rounded-lg bg-primary p-4 text-xl text-white hover:bg-[#303ECE] disabled:bg-gray-2 disabled:text-gray-4"
disabled={isAnyInvalid}
type="submit"
>
{currentLeague ? '수정하기' : '다음으로'}
</Button>
</form>
</div>
);
}
16 changes: 2 additions & 14 deletions src/components/admin/register/League/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,7 @@ import {
usePostLeagueMutation,
usePutLeagueMutation,
} from '@/queries/admin/useLeagueRegister/query';
import {
LeagueDataType,
LeagueRegisterDataType,
SportsDataType,
} from '@/types/admin/league';
import { LeagueDataType, LeagueRegisterDataType } from '@/types/admin/league';
import { updateSet } from '@/utils/set';
import { parseTimeString } from '@/utils/time';

Expand All @@ -33,7 +29,7 @@ export default function RegisterLeague({
);
const [newSportsData, setNewSportsData] = useState<Set<number>>(new Set());

const { leagueData, leagueSportsData, sportsListData } = data;
const { leagueData, sportsListData } = data;
const currentLeague = leagueData.find(e => e.leagueId === Number(leagueId));

const router = useRouter();
Expand All @@ -51,14 +47,6 @@ export default function RegisterLeague({
endAt: parseDate(currentLeague.endAt),
});
}
if (leagueSportsData) {
const reducedSportsData = leagueSportsData.reduce(
(acc, cur) => [...acc, cur.sportId],
[] as SportsDataType,
);

setNewSportsData(new Set(reducedSportsData));
}
}, []);

const { month, date } = parseTimeString(new Date().toString());
Expand Down
8 changes: 4 additions & 4 deletions src/components/common/Sidebar/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
import Link from 'next/link';
import { useEffect, useState } from 'react';

import { getAllLeaguesWithAuth } from '@/api/admin/league';
import { LeagueType } from '@/types/admin/league';
import { getAllLeagues } from '@/api/league';
import { LeagueType } from '@/types/league';

type SidebarProps = {
isSidebarOpen: boolean;
Expand All @@ -15,12 +15,12 @@ export default function Sidebar({
onClickSidebar,
}: SidebarProps) {
const [menuContent, setMenuContent] = useState<LeagueType[]>([
{ name: '전체', leagueId: 0, startAt: '', endAt: '' },
{ name: '전체', leagueId: 0 },
]);

useEffect(() => {
const getLeagueData = async () => {
const res = await getAllLeaguesWithAuth();
const res = await getAllLeagues();

setMenuContent(prev => [...prev, ...res]);
};
Expand Down
1 change: 0 additions & 1 deletion src/types/admin/league.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,5 @@ export type DeleteLeaguePayload = LeagueIdType;

export type LeagueRegisterDataType = {
leagueData: LeagueType[];
leagueSportsData?: SportsCategoriesType[];
sportsListData: SportsCategoriesType[];
};
25 changes: 25 additions & 0 deletions src/utils/LocalStorage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
class LocalStorage {
constructor() {}

static setItem(key: string, value: string) {
if (typeof window !== 'undefined') {
localStorage.setItem(key, value);
}
}

static getItem(key: string) {
if (typeof window !== 'undefined') {
return localStorage.getItem(key);
}

return null;
}

static removeItem(key: string) {
if (typeof window !== 'undefined') {
localStorage.removeItem(key);
}
}
}

export default LocalStorage;

0 comments on commit 8339bf2

Please sign in to comment.