강의

멘토링

커뮤니티

Cộng đồng Hỏi & Đáp của Inflearn

Hình ảnh hồ sơ của nobleser9617
nobleser9617

câu hỏi đã được viết

Next.js vừa tầm một miếng ăn

4.1) Fetching dữ liệu trong App Router

params부분 에러

Đã giải quyết

Viết

·

389

0

fetch 부분에서 다음과 같이 작성하였는데 params.id부분에서 id 부분에
Property 'id' does not exist on type 'Promise<{ id: string | string[]; }>'.ts(2339)

이러한 에러가 발생합니다.

 const result = await fetch(
    `${process.env.NEXT_PUBLIC_API_SERVER_URL}/book/${params.id}`
  );
reacttypescriptnext.js

Câu trả lời 3

0

winterlood님의 프로필 이미지
winterlood
Người chia sẻ kiến thức

안녕하세요 이정환입니다.

params는 Promise로 래핑된 비동기 객체입니다. 따라서 내부의 값을 꺼내 사용하시려면 await를 통해 비동기 작업이 끝나기 까지 기다렸다가 그 결과값을 꺼내 사용하셔야 합니다. 마치 const {id} = await params 처럼 말이죠 😃

자세한 내용은 우리 강의의 3.2) 페이지 라우팅 설정하기 12분 02초 경에 설명 드리고 있으니 해당 부분만 짧게 다시 수강하시는 것도 추천드립니다!

 

0

nobleser9617님의 프로필 이미지
nobleser9617
Người đặt câu hỏi

일단 이렇게 parmas를 await으로 감싸니 해결됐는데 이게 맞는 방법일까요?

    `${process.env.NEXT_PUBLIC_API_SERVER_URL}/book/${(await params).id}`

0

nobleser9617님의 프로필 이미지
nobleser9617
Người đặt câu hỏi

전체 코드도 첨부 하겠습니다

import style from "./page.module.css";

export default async function Page({
  params,
}: {
  params: Promise<{ id: string | string[] }>;
}) {
  const result = await fetch(
    `${process.env.NEXT_PUBLIC_API_SERVER_URL}/book/${params.id}`
  );
  if (!result.ok) {
    return <div>에러 발생 ...</div>;
  }

  const book = await result.json();

  const { id, coverImgUrl, title, subTitle, author, publisher, description } =
    book;

  return (
    <div className={style.container}>
      <div
        className={style.cover_img_container}
        style={{ backgroundImage: `url('${coverImgUrl}')` }}
      >
        <img src={coverImgUrl} />
      </div>
      <div className={style.title}>{title}</div>
      <div className={style.subTitle}>{subTitle}</div>
      <div className={style.author}>
        {author} | {publisher}
      </div>
      <div className={style.description}>{description}</div>
    </div>
  );
}
Hình ảnh hồ sơ của nobleser9617
nobleser9617

câu hỏi đã được viết

Đặt câu hỏi