react-query: 是否有一个无论是否缓存 getQuery 都会触发的回调?

react-query: is there a callback that get trigger regardless of whether getQuery is cached or not?

我想在获取数据后执行一些副作用,例如 setState 和更新上下文。但是,当数据在缓存中时,不会执行 onSuccess。 useEffect 也不起作用,因为如果数据被缓存,它不会从未定义的数据变为真实数据。因此它也不会被触发。这样做的最佳方法是什么?谢谢

My usecase is to extract some values from the data returned from useQuery and set a new state on those.

通常,他们不应该需要将状态从 react-query 复制到本地状态。这只会导致真相来源的重复。最好将它们分开,这样您也可以从后台更新中获益。

如果要转换数据或订阅部分数据,请使用 useQueryselect 选项:

const { data } = useQuery(key, fn, { select: data => data.map(...) })

或者,您可以根据 useMemo 返回的数据计算一些新数据,例如:

const { data } = useQuery(...)

const articles = useMemo(() => data?.map(...), [data])
// work with articles from here on

您也可以将其很好地放入自定义挂钩中。