react-query v4 공식문서 : Default Query Function

👾·2022년 8월 12일
0

react-query

목록 보기
27/27
post-thumbnail

공식문서 : https://tanstack.com/query/v4/docs/guides/default-query-function

Default Query Function

어떤 이유로든 전체 앱에 대해 동일한 쿼리 함수를 공유하고 쿼리 키를 사용하여 fetch할 항목을 식별할 수 있기를 원하는 경우, 다음과 같은 기본 쿼리 함수를 React Query에 제공하여 수행할 수 있다. :

// Define a default query function that will receive the query key
const defaultQueryFn = async ({ queryKey }) => {
  const { data } = await axios.get(`https://jsonplaceholder.typicode.com${queryKey[0]}`);
  return data;
};

// provide the default query function to your app with defaultOptions
const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      queryFn: defaultQueryFn,
    },
  },
})

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <YourApp />
    </QueryClientProvider>
  )
}

// All you have to do now is pass a key!
function Posts() {
  const { status, data, error, isFetching } = useQuery(['/posts'])

  // ...
}

// You can even leave out the queryFn and just go straight into options
function Post({ postId }) {
  const { status, data, error, isFetching } = useQuery([`/posts/${postId}`], {
    enabled: !!postId,
  })

  // ...
}

기본 쿼리 함수를 재정의하고 싶다면, 평소처럼 직접 제공하면 된다.

0개의 댓글