Router.query 받아오기

이재진·2023년 11월 20일
0

모애프로젝트

목록 보기
10/16

검색기능을 만드는 도중에 발생한 문제...

상황

검색기능을 완성시켰는데, 이게 왠걸 첫 값으로 받아오는 query가 undefined가 뜨는 바람에 내가 검색하고 싶은 단어를 담아서 api로 쏴줘야 하는데, 그러지 못해서 에러가 자꾸 떴다...

생각해보기

nextjs의 특징때문에 생기는 것이라고 판단했다. 지금까지 프로젝트를 진행하면서 그런적이 많았기 때문에...
찾아보니깐 역시나... next.js는 렌더링된 후 쿼리 객체를 채운다는 특징을 가지고 있었다.
router를 console찍어보면 나오는 router.isReady를 활용하려고 했는데, 생각처럼 적용이 되질 않았다. 이건 아마 내 문제인듯...

해결

검색해보니깐 getServerSideProps를 사용해서 해결하는 방법이 있었다. 그래서 구글링하면서 찾아보며 작성해 보았다.
공식문서

export async function getServerSideProps(context) {
  const res = await fetch(`https://.../data`)
  const data = await res.json()
 
  return {
    props: { data }, // will be passed to the page component as props
  }
}

공식문서에 나와있는 코드이다. 이 코드를 우리 프로젝트에 맞게 typescript로 바꿨다.

interface TotalPageProps {
  total : number,
}

...

export const getServerSideProps: GetServerSideProps<TotalPageProps> = async (
  context,
) => {
  const query = context.query;
  try {
    const totalPage = await SEARCH.searchApi(
      query.part as string,
      query.searchQuery as string,
      1,
      1,
      '전체',
    );
    const tempPage = Math.ceil(totalPage.meta.total / 16);
    return { props: { total: tempPage } };
  } catch (error) {
    console.error('Error fetching data:', error);
    return {
      props: {
        total: 0,
      },
    };
  }
};

검색어를 검색하면, 백엔드에서 해당 검색가 들어있는 게시판의 정보를 넘겨준다. 거기서 검색된 게시물 개수를 불러와서 그 값을 전달해주었다.

여기서 문제가 발생했는데, 분명 나는 인터넷에 나온대로 했는데, getServerSideProps 자체가 동작이 되지 않았다.

여기 저기 뒤지가다 찾아보니깐 pages 폴더 하위에서 작성해야 실행된다고 한다...
그래서 원래는 components폴더 하위에 작성했던 걸 pages로 바꿨다...

처음에는 그냥 작성했는데

export const getServerSideProps: GetServerSideProps<TotalPageProps> = async (
  context,
) => {
  const query = context.query;
    const totalPage = await SEARCH.searchApi(
      query.part as string,
      query.searchQuery as string,
      1,
      1,
      '전체',
    );
    const tempPage = Math.ceil(totalPage.meta.total / 16);
    return { props: { total: tempPage } };
};

이렇게 작성하니깐 next.js에서 페이지를 못 불러오는 에러가 났다.

찾아보니깐 getServerSideProps를 사용하면, 나는 에러란다.
그래서 try~catch문을 써서 오류를 잡을 수 있었다.

export const getServerSideProps: GetServerSideProps<TotalPageProps> = async (
  context,
) => {
  const query = context.query;
  try {
    const totalPage = await SEARCH.searchApi(
      query.part as string,
      query.searchQuery as string,
      1,
      1,
      '전체',
    );
    const tempPage = Math.ceil(totalPage.meta.total / 16);
    return { props: { total: tempPage } };
  } catch (error) {
    console.error('Error fetching data:', error);
    return {
      props: {
        total: 0,
      },
    };
  }
};

이 값들을 전달해서, 페이지 수를 얻을 수 있었다.


전체코드

import SEARCH from '@/apis/search';
import PostBoardTemplates from '@/components/templates/post-temp/PostTemplates';
import AllPost from '@/components/veiws/AllPost';
import { GetServerSideProps, NextPage } from 'next';

interface TotalPageProps {
  total: number;
}

const Home: NextPage<TotalPageProps> = ({ total }) => {
  return (
    <>
      <PostBoardTemplates main="전체" totalPage={total} />
      {/* <AllPost /> */}
    </>
  );
};

export const getServerSideProps: GetServerSideProps<TotalPageProps> = async (
  context,
) => {
  const query = context.query;
  try {
    const totalPage = await SEARCH.searchApi(
      query.part as string,
      query.searchQuery as string,
      1,
      1,
      '전체',
    );
    const tempPage = Math.ceil(totalPage.meta.total / 16);
    return { props: { total: tempPage } };
  } catch (error) {
    console.error('Error fetching data:', error);
    return {
      props: {
        total: 0,
      },
    };
  }
};

export default Home;
profile
나의 뇌를 Refactoring

0개의 댓글

Powered by GraphCDN, the GraphQL CDN