'Same function for all queries onSuccess react-query

I have a use-case where I would like to run the same function onSuccess for all mutations and queries globally instead of having to set the same function on each individual query (i have a lot of queries)

I have a bunch of queries like so

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"
}

However, I would like to set this globally for all quires, something like this

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));
});

I have searched the docs for about an hour for this type of functionality but cannot find anything



Solution 1:[1]

There is an open PR for that exact use case: https://github.com/tannerlinsley/react-query/pull/2404

It adds the possibility to have a global onSuccess callback on the queryCache.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 TkDodo