aotoyae

[Next] React Query 본문

Next

[Next] React Query

aotoyae 2024. 3. 15. 02:14

 

 

💡 Next.js 에서 리액트 쿼리 사용하기!

 

리액트에서와 별반 다르지 않다! 우선 프로젝트를 만든 후에 ~

yarn add @tanstack/react-query

 

app/provider.tsx 생성

'use client'; // ** 필수! 클라이언트 컴포넌트에서만 사용 가능하다!

import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

const QueryProvider = ({ children }: React.PropsWithChildren) => {
  const queryClient = new QueryClient();

  return (
    <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
  );
};

export default QueryProvider;

🚨 layout 에 바로 안 만들고 provider 로 분리한 이유는..

RootLayout 은 클라이언트 컴포넌트로 쓸 수 없어서! (그 외 컴포넌트는 모두 가능)

 

 

layout.tsx

import QueryProvider from './provider';

//...

  return (
    // ...
    <QueryProvider>  <!-- children 을 감싸준다 -->
      <div className="flex justify-center text-center bg-indigo-50">
        {children}
      </div>
    </QueryProvider>
    // ...
    );
}

 

todos-csr/page.tsx

function TodosPage() {
  const queryClient = useQueryClient();

// ...

  const newTodoMudation = useMutation({
    mutationFn: async (newTodo: newTodo) => {
      const response = await fetch('http://localhost:3000/api', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(newTodo),
      });

      const todo = await response.json();
      return todo;
    },
  });

  const onSubmitHandler = (e: FormEvent) => {
    e.preventDefault();
    newTodoMudation.mutate(
      { title, contents },
      {
        onSuccess: () => {
          setTitle('');
          setContents('');

          queryClient.invalidateQueries({
            queryKey: ['todos'],
          });
        },
      }
    );
  };
  
// ...