개인공부/Next.js
Next.js 13 (저번 클론 코딩에서 추가) #2
BTSBRINGMEHERE
2023. 5. 31. 13:21
App 디렉토리
12 버전까지만 해도 라우터 구조가 pages 디렉토리에서 구성을 해야했고 13버전으로 업그레이드 되면서 next.config.js에서
/** @type {import('next').NextConfig} */ const nextConfig = { experimental: { appDir: true } ... } module.exports = nextConfig
이런식으로 구조를 완성하고 app 디렉토리에서 구성을 할 수 있었습니다.
하지만, 2주전? 부터 next를 설치하면서 /app 디렉토리 구성요소를 할지 말지 물어보고 Yes를 하면 자동으로 app 디렉토리가 자동으로 완성이 됩니다. 즉, next.config.js에서 설정을 안해줘도 알아서 됩니다.
리스트, 예약 prisma create, update하기
import { PrismaClient } from "@prisma/client";
// prismaClient를 전역에서 선언 (추가 공부 필)
declare global {
var prisma: PrismaClient | undefined;
}
const client = globalThis.prisma || new PrismaClient();
if (process.env.NODE_ENV !== "production") globalThis.prisma = client;
export default client;
우선 prisma를 client에 가져옵니다.
// 서버 부분임
import { NextResponse } from "next/server";
import prisma from "@/app/libs/prismadb";
// POST function
export async function POST(request: Request) {
// prisma db 중 listing 구조를 가져옴
const body = await request.json();
const {
title,
description,
imageSrc,
category,
roomCount,
bathroomCount,
guestCount,
location,
price,
} = body;
// value가 없으면 에러
Object.keys(body).forEach((value: any) => {
if (!body[value]) {
NextResponse.error();
}
});
// 새로운 Listing 구조를 만듦
const listing = await prisma.listing.create({
data: {
title,
description,
imageSrc,
category,
roomCount,
bathroomCount,
guestCount,
locationValue: location.value,
price: parseInt(price, 10),
userId: currentUser.id,
},
});
return NextResponse.json(listing);
}
예약할 때
import { NextResponse } from "next/server";
import prisma from "@/app/libs/prismadb";
export async function POST(request: Request) {
const body = await request.json();
const { listingId, startDate, endDate, totalPrice } = body;
if (!listingId || !startDate || !endDate || !totalPrice) {
return NextResponse.error();
}
// 해당 id의 조건이 붙고 data가 update가 됨
const listingAndReservation = await prisma.listing.update({
where: {
id: listingId,
},
data: {
reservations: {
create: {
userId: currentUser.id,
startDate,
endDate,
totalPrice,
},
},
},
});
return NextResponse.json(listingAndReservation);
}
pirsma로 생성한 db,즉 mongodb에 저장된 db구조를 body 객체로 가져와서 해당 db를 prisma.listing.create로 생성하고 prisma.listing.update로 업데이트를 해줍니다.
서버와 클라이언트
funtion Client() {
const [value, setValue] = useState("");
return (
<>
<p>{value}</p>
</>
)
}
function getServerSideProps: GetServerSideProps<T> () {
const a = axios.create(...)
return a.data.json()
}
function getStaticSiteProps:GetStaticProps<T> () {
const a = axios.create(...)
return {
a.json()...
revalidate: 5 * 60
}
}
기존에는 이런 구조에서 하나의 페이지에서 SSR, SSG 함수를 사용을 했지만
//Client.tsx
"use client"
function Client() {
}
//server.ts
function POST() {
}
현재는 다른 페이지에서 사용가능하며 client로 사용할때 "use client" 하나만 선언해 주면 됩니다.
정리
- 이 클론코딩 영상도 3월쯤에 찍고 영상도 올린지 한달도 안됐는데 클론코딩 시작하면서 next 13.4로 업데이트 되면서 처음 설치할 때 app구조 유무를 물어봅니다. 그리고 이제 config에 선언을 안하고 app구조로 자동으로 사용이 가능합니다.
- prisma.<table이름>.<create | update | delete>로 db를 업데이트 할 수 있습니다.
- 12버전과 다르게 13버전에서는 "use client"하나만 선언해주면 client로써 동작이 됩니다.(useEffet, useCallback 등의 리액트 함수를 사용할 때는 무조건 use Client)
참조
홍보는 아니고 tailwind, typescript, next13을 같이 배우기 좋은 영상인듯 합니다.