【发布时间】:2021-07-07 15:29:47
【问题描述】:
我有一个用例,我想在全局范围内为所有突变和查询运行相同的函数onSuccess,而不必为每个单独的查询设置相同的函数(我有很多查询)
我有一堆这样的查询
const q1 = useQuery(
"q1",
async () => {
return await axios
.get(`/some/path`)
.then((res) => res.data)
.catch((e) => CustomError(e));
},
{
onSuccess: () => generic(),
}
);
const q2 = useQuery(
"q2",
async () => {
return await axios
.get(`/some/path`)
.then((res) => res.data)
.catch((e) => CustomError(e));
},
{
onSuccess: () => generic(),
}
);
const q1 = useQuery(
"q3",
async () => {
return await axios
.get(`/some/path`)
.then((res) => res.data)
.catch((e) => CustomError(e));
},
{
onSuccess: () => generic()
}
);
function generic() {
return "should be set globally and run on ever OnSuccess event"
}
但是,我想为所有查询全局设置这个,像这样
const queryCache = new QueryClient({
defaultConfig: {
queries: {
onSuccess: () => {
return "should be set globally and run on ever OnSuccess event";
},
},
},
});
const q1 = useQuery("q1", async () => {
return await axios
.get(`/some/path`)
.then((res) => res.data)
.catch((e) => CustomError(e));
});
const q2 = useQuery("q2", async () => {
return await axios
.get(`/some/path`)
.then((res) => res.data)
.catch((e) => CustomError(e));
});
const q1 = useQuery("q3", async () => {
return await axios
.get(`/some/path`)
.then((res) => res.data)
.catch((e) => CustomError(e));
});
我已经为此类功能搜索了大约一个小时的文档,但找不到任何东西
【问题讨论】:
-
和react-query有关吗?您可以使用处理成功的函数包装所有请求。比如:
function callAPI(path) { return axios.get(path).then((res) => res.data).catch((e) => CustomError(e) },然后是const q1 = useQuery("q3", () => callAPI('some/path'))。 -
这与我已有的代码没有什么不同,也没有解决这个问题。不过还是谢谢。
-
嗯,它确实不同,因为你处理一次成功,在那里你可以打电话给
generic(),但如你所愿:)
标签: reactjs react-query