[TanStakQuery] Default Query Function

Jeris·2023년 5월 22일

어떤 이유로든 전체 앱에 대해 동일한 쿼리 함수를 공유하고 쿼리 키를 사용하여 fetch할 항목을 식별하고 싶을 경우, TanStack 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({ queryKey: ['/posts'] })

  // ...
}

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

  // ...
}

기본 queryFn을 override하고 싶다면 평소처럼 자신만의 쿼리를 제공하면 됩니다.

Reference

profile
job's done

0개의 댓글