有没有办法在React-Query的QueryClient上配置基本URL?

发布于 2025-02-07 19:38:22 字数 242 浏览 2 评论 0原文

好吧,我有一个非常简单的文件,可以从React-Query库中导出一个QueryClient:

/QueryClient.ts,

import { QueryClient } from "react-query";

export const queryClient = new QueryClient();

有没有办法设置基本URL,还是我应该使用诸如上下文提供商之类的东西来做到这一点?

Well, I have this very simple file where I export a QueryClient from react-query library:

/queryClient.ts

import { QueryClient } from "react-query";

export const queryClient = new QueryClient();

Is there a way to set up a base url, or should I use something like context provider in order to do it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

oО清风挽发oО 2025-02-14 19:38:23

好吧,如本文所示:

“ https://tkdodo.eu/blog/reaect-query-and-ytype-script”

默认查询函数

您可以配置默认查询函数:

export const queryClient = new QueryClient({
    defaultOptions: {
        queries: {
            queryFn: async ({ queryKey: [url] }) => {
                if (typeof url === 'string') {
                    const { data } = await axios.get(`${BASE_URL}/${url.toLowerCase()}`)
                    return data
                }
                throw new Error('Invalid QueryKey')
            },
        },
    },
});

能够调用useQuery实例仅通过您的API方法的参数来调用:

// 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,
   })
 
   // ...
 }

Well, as shown in this article:

React Query and TypeScript

And on the docs:

Default Query Function

You can configure a default query function:

export const queryClient = new QueryClient({
    defaultOptions: {
        queries: {
            queryFn: async ({ queryKey: [url] }) => {
                if (typeof url === 'string') {
                    const { data } = await axios.get(`${BASE_URL}/${url.toLowerCase()}`)
                    return data
                }
                throw new Error('Invalid QueryKey')
            },
        },
    },
});

Being able to call the UseQuery instance passing only the params of your api method call:

// 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,
   })
 
   // ...
 }
我一向站在原地 2025-02-14 19:38:23

ReactQuery是包装器。提出请求的不是工具。您不能在其中定义基本URL。如果您需要配置网络请求,则需要在执行请求的工具上进行操作,而不是在包装器上进行。您可以为fetch api或axios软件包设置默认配置

axios.defaults.baseURL = <base_url>

。代码>查询或突变,将使用此基本URL。

但是,如果由于某种原因您实际上需要配置ReactQuery本身而无需触摸HTTP客户端,则可以定义默认的突变QUERY> QUERY> QUERY正如您在上一个答案中指出的那样,请按照您想要的方式使用HTTP客户端。但这不是灵活的,因为您不仅定义了基本URL,还可以定义整个查询功能。如果在某些情况下需要其他QueryFN或MUTATIONFN,则必须再次指定基本URL。

从文档( https://tanstack.com/查询/v4/docs/framework/react/guides/default-Query-function ):

// 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,
    },
  },
})

reactQuery is a wrapper. It is not the tool that makes the request. You cannot define a base url in it. If you need to configure the network request, you need to do it on the tool that does the request, not on the wrapper. You can set a default configuration for the fetch API or for the axios package, for example:

axios.defaults.baseURL = <base_url>

That way, when you use axios in a query or mutation, this base url will be used.

However if for some reason you actually need to configure reactQuery itself without touching the HTTP client, you can define a default mutation or query function that will use the HTTP client the way you want, as you pointed out in the previous answer. But that is less flexible, as you don't just define a base url, but the whole query function. If you need a different queryFn or mutationFn in some case, then you have to specify the base url again.

From the docs (https://tanstack.com/query/v4/docs/framework/react/guides/default-query-function):

// 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,
    },
  },
})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文