교육 (Today I Learned)/Hanaro

[Hanaro] 34일차 / Next.js (Data Fetching)

Bay Im 2024. 3. 8. 00:11

09 Next.js - CSR, SSR, SSG, ISR

  • Data Fetch Sample
    • CSR (Client Side Rendering)
      • 파일에 최상단에 ‘use client’; 작성
    • SSG (Static Site Generation)
      • getStaticProps
      • cache: “no-store”
    • SSR (Server Side Rendering)
      • getServerSideProps
      • cache: “force-cache”
    • ISR
      • next: { revalidate: 초, }

 

프론트엔드 실습 과제 풀이 시간

  • 구현하지 못한 내역
    • 세션 컨텍스트 구현하지 못한 것
      • 풀이 코드 (session-context.tsx)
      import {
        createContext,
        PropsWithChildren,
        useContext,
        useEffect,
        useReducer,
      } from 'react';
      import {
        DefaultSession,
        getStorage,
        Session,
        setStorage,
      } from '../libs/storage-utils';
      import { useFetch } from './fetch';
      import { useNavigate } from 'react-router-dom';
      
      const SessionContext = createContext<{
        login: (userId: number) => boolean;
        logout: () => void;
        session: Session;
      }>({
        login: () => false,
        logout: () => {},
        session: DefaultSession,
      });
      
      const reducer = (session: Session, payload: Session | null) => {
        session = payload || DefaultSession;
        setStorage(session);
        return session;
      };
      
      export const SessionProvider = ({ children }: PropsWithChildren) => {
        const [session, dispatch] = useReducer(reducer, DefaultSession);
        const navigate = useNavigate();
      
        const login = (userId: number) => {
          if (!userId || userId < 1 || userId > 10) return false;
      
          dispatch({ id: userId, username: '' });
          return true;
        };
      
        const logout = () => {
          dispatch(null);
          navigate('/');
        };
      
        const { data } = useFetch<Session>({
          url: `users/${session.id}`,
          dependencies: [session.id],
          defaultData: DefaultSession,
          enable: !!session.id,
        });
      
        useEffect(() => {
          if (data) {
            const { id, username } = data;
            dispatch({ id, username });
          }
        }, [data]);
      
        useEffect(() => {
          dispatch(getStorage());
        }, []);
      
        return (
          <SessionContext.Provider value={{ login, logout, session }}>
            {children}
          </SessionContext.Provider>
        );
      };
      
      // eslint-disable-next-line react-refresh/only-export-components
      export const useSession = () => useContext(SessionContext);

 

기타

  • clsx 모듈 에러
    • 에러 메시지
      • import clsx from 'clsx'; 에서 Cannot find module 'clsx' or its corresponding type declarations.
    • 해결 방법
      • cmd 창 프로젝트 최상단 디렉터리에서 npm install clsx 입력