微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将项目添加到列表时,乐观响应不起作用

如何解决将项目添加到列表时,乐观响应不起作用

我的数据模型是一个包含项目的列表。很简单:

{
  _id: 1,name: "List 1",items: [
    { _id: 2,text: "Item text 1" },{ _id: 3,text: "Item text 2" }
   ]
}

添加具有乐观响应的新列表非常有效:

  const [addListMutation] = useAddListMutation({
    update: (cache,{ data }) => {
      const cachedLists =
        (cache.readQuery<GetAllListsQuery>({
          query: GetAllListsdocument,})?.lists as TList[]) ?? [];

      if (data) {
        cache.writeQuery({
          query: GetAllListsdocument,data: {
            lists: [...cachedLists,data?.list as TList],},});
      }
    },});
  
  const addList = async (name: string) => {
    const list = {
      _id: ..new id here,name,items: [],};

    const variables: AddListMutationVariables = {
      data: list,};

    await addListMutation({
      variables,optimisticResponse: {
        list,});
  };

这会使用 const { loading,data } = useGetAllListsQuery(); 立即反映在我的组件中。数据更新两次;首先是乐观的反应,然后是突变完成后。和预期的一样。

现在我正在尝试以这种方式向列表中添加一个项目

  const [updateListMutation] = useUpdateListMutation({
    update: (cache,{ data }) => {
      const cachedLists =
        (cache.readQuery<GetAllListsQuery>(
          {
            query: GetAllListsdocument,)?.lists as TList[]) ?? [];

      if (data?.list) {
        // Find existing list to update
        const updatedList = data?.list as TList;
        const updatedListIndex = cachedLists.findindex(
          (list: TList) => list._id === updatedList._id,);
      
        // Create a copy of cached lists and replace entire list
        // with new list from { data }.
        const updatedLists = [...cachedLists];
        updatedLists[updatedListIndex] = { ...updatedList };

        cache.writeQuery({
          query: GetAllListsdocument,data: {
           lists: updatedLists,});
      }
    }
  });

  const updateList = async (updatedList: TList) => {
    const variables: UpdateListMutationVariables = {
      query: {
        _id: updatedList._id,set: updatedList,};

    await updateListMutation({
      variables,optimisticResponse: {
        list: updatedList,});
  };

  const addListItem = async (list: TList,text: string) => {
    const updatedList = R.clone(list);

    updatedList.items.push({
      _id: ...new item id here,text: 'My new list item',});

    await updateList(updatedList);
  };

问题是在我的组件中,const { loading,data } = useGetAllListsQuery(); 没有返回我期望的内容。当数据第一次随着乐观响应发生变化时,它包含一个空列表项:

{
  _id: 1,items: [{}]
}

并且只有在突变响应返回后,它才会使用带有文本“我的新列表项”的项目填充项目数组。所以我的组件在突变完成时首先更新,而不是乐观响应,因为它无法确定更新数组。不知道为什么? (并且我已经检查了 writeQuery 中的 updatedLists 数组是否正确包含带有文本“我的新列表项”的新项,因此我正在尝试写入正确的数据)。

如果您有任何提示解决方案,请告诉我。

我尝试过使用缓存(现在它只是初始化认值,如 new InMemoryCache({}))。我可以看到缓存被归一化为一堆 List:1,List:2,... 和 ListItem:3,ListItem:4,... 试图禁用规范化,所以我只有 List:{id} 条目。没有帮助。还尝试将 __typename: 'ListItem' 添加添加的项目,但这只会导致更新中的 { data }: ... 乐观响应未定义。我现在已经用了几个小时了。我正在尝试做的应该是一个相当简单和常见的用例:)

package.json

"@apollo/client": "^3.3.4","graphql": "^15.4.0","@graphql-codegen/typescript": "^1.19.0",

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。