오늘은 챌린지반에서 간단한 실습을 Next.js로 진행하였다. 막상 사용해보니 react 사용과 별 다를 것은 없었다고 생하지만 type을 설정하는 과정이 추가됐다는 것과 라우팅 설정이 다르다는 것을 느꼈고, Next로 프로젝트를 생성할 때 어떤 점을 주의해야하는지에 대해 알게 되었다.
프로젝트는 api를 통해 전세계 국가의 정보를 간단하게 가져오는 것이었다.
상태를 지정할 때에도 타입을 신경써주어야 했고,
const [countries, setCountries] = useState<Country[]>([]);
const [selectedCountries, setSelectedCountries] = useState<Country[]>([]);
api를 통해 받아오는 데이터의 타입도 모두 정해주어야 했다.
export interface Country {
name: {
common: string; // 일반 국가명
official: string; // 공식 국가명
nativeName?: {
[key: string]: {
official: string;
common: string;
};
};
};
population: number; // 인구
region: string; // 대륙
subregion?: string; // 하위 지역
capital?: string[]; // 수도
languages?: { [key: string]: string }; // 언어
flags: {
png: string; // PNG 형식의 국기
svg: string; // SVG 형식의 국기
alt?: string; // 국기 설명
};
};
또한 전달되는 프롭스의 타입도 같이 전달해주어야 했다.
interface CountryCardProps {
country: Country; // Country 타입 데이터
onClick: () => void; // 클릭 핸들러 타입
}
토글 함수는 아래처럼 작성했는데, 이 코드에서도 type 오류 없이 잘 작동하지만 조금 더 명확하게 type을 지정해주는 것이 좋다는 피드백을 받을 수 있었다.
const toggleCountrySelection = (country: Country) => {
setSelectedCountries((prev) => {
const isSelected = prev.some(
(c) => c.name.common === country.name.common
);
if (isSelected) {
// 이미 선택된 경우, 제거
return prev.filter((c) => c.name.common !== country.name.common);
} else {
// 선택되지 않은 경우, 추가
return [...prev, country];
}
});
};
간단한 json-sever를 만들어 Card를 클릭하면 데이터가 전송될 수 있게 끔 하였다.
// fetchCountries
import { Country } from "@/types/country";
export async function fetchCountries(): Promise<Country[]> {
const response: Response = await fetch("https://restcountries.com/v3.1/all", {
method: "GET",
});
if (!response.ok) {
throw new Error("Failed to fetch countries!");
}
return await response.json();
}
// addCountry
export const addCountry = async (country: AddCountryPayload): Promise<void> => {
const response = await fetch("http://localhost:3001/countries", {
method: "POST",
body: JSON.stringify({
official_name: country.official_name,
flag: country.flag,
}),
});
if (!response.ok) {
throw new Error("Failed to add country!");
};
};
// CountryCard
const handleAddCountry = async () => {
try {
const payload: AddCountryPayload = {
official_name: country.name.official,
flag: country.flags.png,
};
await addCountry(payload);
} catch (error) {
console.error("Failed to add country", error);
};
};
'TIL' 카테고리의 다른 글
12. 13. 36일차 TIL Next.js 과제_02 (0) | 2024.12.14 |
---|---|
12. 12. 35일차 TIL next과제 시작 (0) | 2024.12.12 |
12. 10. 33일차 TIL Next.js 시작 (1) | 2024.12.10 |
11. 25. 32일차 TIL (0) | 2024.11.25 |
11. 22. 31일차 TIL 세션, 토큰, 쿠키, JWT (0) | 2024.11.22 |