Study/React

[React] Next.js 실시간 데이터 적용 (cache 삭제)

hyjang 2024. 7. 29. 18:20
728x90

들어가며

  • create에서 POST를 했지만 실시간으로 반영되지 않음
  • fetch에서 정보를 가져오면 Next.js에서는 정보를 캐시(.next 폴더)로 저장한다.
  • next폴더를 삭제하고 다시 생성한다.

  1. rm -rf .next 또는 .next 폴더 삭제
  2. npm run dev
  3. 새로고침
💡 캐시가 삭제되고 개발환경을 다시 실행하면서 json 정보를 가져온다. 마찬가지로 POST를 할 때도 캐시를 삭제하는 작업이 필요하다.

 

Revalidating Data

(...)
export default async function RootLayout({ children }) { 
  const resp = await fetch('<http://localhost:9999/topics>', {next:{revalidate:10}})
  const topics = await resp.json();
  console.log(topics)
  return (
  (...)
💡 10초 동안만 캐시를 유지하고 삭제한다. (데이터 적용 시 10초 뒤에 적용될 수 있다. )

 

Dynamic Data Fetching

export default async function RootLayout({ children }) { 
  const resp = await fetch('<http://localhost:9999/topics>', {cache:'no-store'})
  const topics = await resp.json();
💡 cache 정보를 저장하지 않음

 

- POST 진행 

 fetch(`http://localhost:9999/topics/`,{
                method:"POST",
                headers:{
                    'Content-Type':'application/json'
                },
                body : JSON.stringify({title, body})}
            )
            .then(res => res.json())
            .then(result=>{ 
                const lastid = result.id;
                router.push(`/read/${lastid}`);
                router.refresh();
            })
💡 push 한 다음 refresh를 해야 바로 적용됨

 

  • router.refresh : 사용자가 페이지 내에서 특정 작업을 수행했을 때 서버로부터 최신 데이터를 가져와야 하지만, 페이지 전체를 새로고침하지 않고 현재 상태를 유지하면서 데이터만 업데이트하고 싶을 때 사용할 수 있다. 즉, 클라이언트 쪽 상태(스크롤 위치, 화면 등)을 유지한다. (reload와 다름)

마치며

cache: 'no-store'은 POST나 PUT/PATCH, DELETE에서 사용할 수 있다.

그렇지만 캐시를 이용한 작업은 다양하기 때문에 더 많은 방법이 있을 것이다.