회고

20230526 TIL

Summer.dev 2023. 5. 26. 23:22

next.js에서는 폴더구조를 유의하자

next.js에서는 서버에게 api요청을 간단하게 할 수 있다. pages/api 폴더안에 js 파일로 만들어주는 방법을 사용했는데 처음에 pages 폴더를 app 폴더 안에 생성해서 아무리 get요청을 보내도 404에러가 뜨는 것이다! 공식문서에 구글링에 아무리 찾아봤는데도 안되어서 결국 다시 강의를 보는데 pages폴더가 최상단에 있었다. ㅎㅎ ㅎㅎ ㅎㅎ 이걸로 한 40분을 날림. 

멘토님의 폴더구조 조언

/msgs

export const EMPTY_SEARCH_ALERT: string = '검색어를 입력해 주세요.';

export const ADD_BOOKMARK_MSG: string = ‘북마크에 상품이 추가되었습니다’;

 

자주쓰는 메세지도 저렇게 따로 저장을 해서 import로 사용하면 나중에 수정할때 편리하다.

 

컴포넌트 또한 스토리북 작성시 폴더링을 잘 해서 관련된 파일 한곳에 저장하는것이 좋다.

스토리북 다운받았을 때 자동생성되는 stories 폴더에 저장하는것 보다 위 사진처럼 관련된 파일들 한곳에 저장하는것이 좋다.

 

스토리북 배포하기

Chromatic 사이트에서 get started now 를 따라하면 명령어 단 2 줄에 만들 수 있다.

북마크 별이랑 드롭다운 메뉴만 넣어본 스토리북 배포해봤다!

 

 

데이터 중복 검사(MongoDB)

import { connectDB } from "@/util/database";
export default async function Handler(req, res) {
  if (req.method === "POST") {
    if (req.body.title === "") {
      return res.status(500).json("fill the title");
    }
    try {
        const db = (await connectDB).db("forum");
        let result = await db.collection("post").find({title:req.body.title}).toArray()
        if(result.length===1){
            return res.status(500).json('already exist id')
        }
        result = await db.collection('post').insertOne(req.body)
      return res.status(200).json("완료!").redirect("/list");
    } catch (error) {
      console.error();
    }
  }
}

1. 요청객체의 title과 같은 값이 db에 있다면 요소가 하나 들어있는 배열 생성

2. 배열의 길이가 1이라면 이미 있는 id라는 응답 메세지

3. 아니라면 db에 데이터 추가

 

만난오류

./node_modules/mongodb/lib/cmap/auth/gssapi.js:4:0 Module not found: Can't resolve 'dns'

import { connectDB } from "@/util/database";

를 하지않으면 일어나는 오류

 

app-index.js:32 Warning: You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`.

input에 defaultValue를 써주면 경고 없어짐

 

 

오늘의 뻘짓

try {
      let db = (await connectDB).db("forum");
      let result = await db
        .collection("post")
        .updateOne(
          { _id: new ObjectId(req.body.id) },
          { $set: { title: req.body.title, content: req.body.content } }
        );
        console.log(result);
        res.redirect(302, '/list')
    }

1. 원래 _id 부분에 그냥 냅다 req.body.id 씀 << 이건 없어도 괜찮았음 

=> objectId 의 역할 ? 새로운 id 부여 인자넣어주면 지정 id 사용가능 

2. res.redirect 부분을 updateOne뒤에 바로 붙여씀 << 이게 문제였음

 

Next.js에서 다이나믹 라우팅을 하려면 폴더 안에 [id]폴더를 만들어줘야하는데. 왜방금한것도 까먹지!!