React Query GEF AXIOS实例来自React上下文
我将与Axios客户端一起使用React-Query。我需要创建一些不受静态AXIOS实例的通用组件,但它们将从React上下文中获得。因此,我可以在多个项目之间分享它们。
目前,我周围有一个包装器,这将为我提供Axios实例。这样:
import { useQuery as useReactQuery } from 'react-query';
import { useAxios } from './axios';
export const useQuery = (queryKey, queryFn, options) => {
const axios = useAxios();
return useReactQuery(queryKey, (queryContext) => queryFn(queryContext, axios), options);
};
它有效,但我不喜欢。因为我需要到处导入此包装器而不是原始方法,并且会给项目上的新移民带来头痛(我甚至为此写了Eslint规则)。
有人知道更好的解决方案吗?我找不到更好的东西。
I'm using react-query together with Axios client. I need to create some generic components which are not bound to static Axios instance but they will get instace from React context. So I can share them between multiple projects.
Currently, I have a wrapper around react-query which will provide me Axios instance. Like that:
import { useQuery as useReactQuery } from 'react-query';
import { useAxios } from './axios';
export const useQuery = (queryKey, queryFn, options) => {
const axios = useAxios();
return useReactQuery(queryKey, (queryContext) => queryFn(queryContext, axios), options);
};
It works but I don't like it. Because I need to import everywhere this wrapper instead of original method and it causes headaches for newcomers on project (I even wrote eslint rule for that).
Does anybody know a better solution? I was unable to find anything better.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这似乎是一个很好的解决方案,也是自定义挂钩的目的。新移民可能应该适应当前代码库的操作,如果每个人都使用您的自定义
usequery
,他们也将使用它。如果没有useaxios
,他们将如何提出正确的请求?您也可以使用现有的ESLINT规则 noflow noreferrer'> no-restruction-imports 直接禁止从
react-Query
导入usequery
。最后,如果没有
react-Query
,您将如何做不同的事情?您可能还会有自定义挂钩调用useaxios
,并产生useffect
左右。因此,实际上,自定义挂钩完全可以:)This seems like a fine solution and also what custom hooks are for. Newcomers should probably adjust to what the current code-base is doing, and if everyone uses your custom
useQuery
, they will also use it. How would they make a correct request withoutuseAxios
?You can also use the existing eslint rule no-restricted-imports to disallow directly importing
useQuery
fromreact-query
.Lastly, how would you do this differently without
react-query
? You'd likely also have custom hook that callsuseAxios
and spawns auseEffect
or so. So really, the custom hook is totally fine :)