我想将经过身份验证的用户放入 zustand 商店。我使用 react-query 获得经过身份验证的用户,这会导致一些问题。我不确定我为什么要这样做。我希望与身份验证相关的所有内容都可以在钩子(Hook)中访问,所以我认为 zustand 是一个不错的选择。
这是获取授权用户的钩子(Hook):
const getAuthUser = async () => {
const { data } = await axios.get<AuthUserResponse>(`/auth/me`, {
withCredentials: true,
});
return data.user;
};
export const useAuthUserQuery = () => {
return useQuery("auth-user", getAuthUser);
};
我想在这个商店中放置授权用户:
export const useAuthStore = create(() => ({
authUser: useAuthUserQuery(),
}));
这是我得到的错误:
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons.
you can read about it in the react documentation: https://reactjs.org/warnings/invalid-hook-call-warning.html
(为了便于理解,我在这篇文章中更改了一些函数的名称。useMeQuery = useAuthUserQuery)
我明白这个错误,但我不知道如何修复它。
最佳答案
这里的误解是您不需要将来自 React 查询的数据放入任何其他状态管理解决方案中。 React query 本身就是一个全局状态管理器。你可以这样做:
const { data } = useAuthUserQuery()
在每个需要数据的组件中。 React 查询将自动尝试通过后台重新获取来更新您的数据。如果您的资源不需要它,请考虑设置 staleTime
。
———
也就是说,如果你真的想把来自 react-query 的数据放入 zustand,在 zustand 中创建一个 setter 并在查询的 onSuccess 回调中调用它:
useQuery(key, queryFn, { onSuccess: data => setToZustand(data) })
https://stackoverflow.com/questions/68690221/