【问题标题】:React Query update changes after mutation突变后反应查询更新变化
【发布时间】:2023-01-20 08:25:15
【问题描述】:

我能够更新服务器端的更改,但它不会实时更新客户端。

export const updateProfiles = async (payload: Profile[]) => {
  let { error, data } = await supabase.from("profiles").upsert(payload);

  return error ? error : data;
};

export const useProfileMutation = () => {
  const queryClient = useQueryClient();
  return useMutation((payload: Profile[]) => updateProfiles(payload), {
    onSuccess: () => queryClient.invalidateQueries(["profiles", "user"]),
  });
};

我正在获取 userprofiles 的数据

export const useProfiles = () => {
  return useQuery(["profiles"], getProfiles);
};

export const useUser = () => {
  return useQuery(["user"], getUser);
};

我有一个页面,我看到来自 profiles 的一些特定用户,当我导航到该页面时,我将用户设置为

  const { data, isLoading } = useProfiles();

  if (isLoading) return <div></div>;

  const profiles = data as Profile[];
  const target = profiles.filter((item) => item.id == id)[0];

如果我导航到主页然后导航回该页面,数据是最新的,但是当我在数据库中更改它时它不会实时更新。

我检查了 console.log 是否触发了 onSuccess 并且它工作正常。当我打电话给queryClient.invalidadeQueries(["profiles", "user"])时,它不应该再次获取它并保持数据最新吗?

【问题讨论】:

    标签: reactjs next.js react-query supabase


    【解决方案1】:

    queryClient.invalidadeQueries(["profiles", "user"]) 使键匹配 ["profiles","user", ...] 的查询无效。你想调用它两次

    queryClient.invalidateQueries(["profiles"])
    queryClient.invalidateQueries(["user"])
    

    或使用谓词版本。文档:https://tanstack.com/query/v4/docs/guides/query-invalidation

    【讨论】:

    • 您只需要将invalidadeQueries 编辑为invalidateQueries 并感谢您的回答
    • 谢谢@AhmedRadi
    猜你喜欢
    • 2020-06-08
    • 2017-07-21
    • 1970-01-01
    • 2018-11-02
    • 2019-12-06
    • 2018-09-23
    • 2020-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多