next에서 getInitialProp는 권고하지 않고, getStaticProps, getServerSideProps를 사용하라고 권고
이번 프로젝트에서 페이지 앱인경우 공통으로 header값을 가져와야하는 케이스
모든페이지에 getServerSideProps를 사용할수없으니
_app.tsx에서 공통으로 처리하려고 함
그래서 getInitialProps를 사용해서 처리
getInitialProps는 getServersideProps보다 먼저 실행됨
둘다 서버에서 실행되는것으로 서버에서 header정보를 가져올 수있음
최신 next에서는 서버컴포넌트에서는 아래처럼 사용함
https://nextjs.org/docs/app/api-reference/functions/headers
이번 프로젝트는 서버 컴포넌트를 사용하지 않아서 getinitialProps를 사용해서 처리했다.
import type { AppProps as NextAppProps, AppContext } from 'next/app';
import { NextPage } from 'next';
import { useEffect } from 'react';
type NextPageWithLayout = NextPage & {
getLayout?: (page: React.ReactElement) => React.ReactNode;
isAuthPage?: boolean;
};
type AppProps = {
Component: NextPageWithLayout;
} & NextAppProps;
const App = ({ Component, pageProps }: AppProps) => {
useEffect(() => {
if (pageProps.deviceuuid) {
authStore.setDeviceUuid(pageProps.deviceuuid);
}
}, [router.isReady]);
}
App.getInitialProps = async ({ Component, ctx }: AppContext) => {
let pageProps = {};
if (Component.getInitialProps) {
pageProps = await Component.getInitialProps(ctx);
}
const header = ctx.req?.headers;
const deviceUuid = header && header['device-uuid'] ? header['device-uuid'] : '';
pageProps = { ...pageProps, deviceuuid: deviceUuid };
return { pageProps };
};'React' 카테고리의 다른 글
| react-query resetQueries, removeQueries (0) | 2023.12.05 |
|---|---|
| react tailwind setting, config (0) | 2023.10.29 |
| React Query Promise.all, useQueries (0) | 2023.09.15 |
| react 프로젝트에서 import순서 정렬 (0) | 2023.09.08 |
| react-hook-form validate with zod (0) | 2023.08.17 |