首页 > 解决方案 > 对所有查询都使用相同的功能 onSuccess raect-query

问题描述

我有一个用例,我想在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));
});

我已经为此类功能搜索了大约一个小时的文档,但找不到任何东西

标签: reactjsreact-query

解决方案


有一个针对该确切用例的公开 PR:https ://github.com/tannerlinsley/react-query/pull/2404

它增加了在 queryCache 上进行全局 onSuccess 回调的可能性。


推荐阅读