所有查询的相同功能 onSuccess 反应查询

Same function for all queries onSuccess react-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));
});

我已经在文档中搜索了大约一个小时以了解此类功能,但找不到任何内容

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

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

我能够找到如何为我的用例解决这个问题,这是一个使用 setDefaultOptions.

设置 OnSuccess 函数的案例

结果是这段代码

const queryCache = new QueryClient({
  defaultConfig: {
    queries: {
      onSuccess: () => {
        return "should be set globally and run on ever OnSuccess event";
      },
    },
  },
});

没有做任何事情,而是通过函数

设置了默认值
const queryCache = new QueryClient();

queryCache.setDefaultOptions({
  queries: {
    refetchOnWindowFocus: false,
    onSuccess: () => console.log("Got IM!"),
  },
});

每次我调用 API 时都会触发 console.log("Got Im!") onSuccess,这是我的用例所需的结果。

我可以看到 const queryCache = new QueryClient(); 确实有一个采用 defaultOptions 的构造函数,但是,无论出于何种原因,它们都没有设置。

编辑

事实证明它确实可以将它传递给构造函数,只是这段代码是在使用旧版本的 react-query 时编写的,当时键是 defaultConfig 而不是 defaultOptions。此代码也有效(以及上述解决方案)

const queryCache = new QueryClient({
  defaultOptions: {
    queries: {
      onSuccess: () => console.log("Got IM!"),
    },
  },
});