React apollo not update data after mutation

我只是一个虾纸丫 提交于 2021-01-28 08:08:16

问题


I have user and user update form, but the problem is that user data in a web app is not updated after mutation.

mutation:

  mutation UserUpdate($user: UserUpdateInput!, $id: String!) {
    userUpdate(user: $user, id: $id) {
      id
    }
  }

query:

  query UsersItemQuery($id: String!) {
    userById(id: $id) {
      id
      email
      datetime
      firstName
      lastName
      middleName
      phone
      role
      podcasts {
        id
        title
      }
    }
  }

I use it on my UserItem.tsx component:

const usersItem = useQuery<UsersItemQuery, UsersItemQueryVariables>(usersItemQuery, { variables })

Problem is after mutation usersItem is the same as before, but it`s become correct after page refresh


回答1:


You seem to be assuming that the cache is updated from your input type. While this seems like something a smart cache might be able to do, we have to keep in mind, that GraphQL makes no assumptions about the shape of mutations and what has been updated. Not all mutations follow the the simple schema of UpdateInputObject + ID. So only the implementation knows what really gets updated and the client making assumptions about this could go really wrong. The implementation may give hints though on which objects have been updated by providing a result type as discussed in the next paragraph.

GraphQL allows us to let mutations return a payload that contains updated items. It becomes a task of good mutation design to return all the updated items.

Your schema seems to allow fetching fields on the updated user but your mutation does not query any updated fields. You should either fetch all the fields that your app needs (e.g. by using the same fragment in the userById query and the mutation) or simply fetch all fields that are updated through the mutation:

  mutation UserUpdate($user: UserUpdateInput!, $id: String!) {
    userUpdate(user: $user, id: $id) {
      email
      datetime
      firstName
      lastName
      middleName
      phone
      role
      podcasts {
        id
        title
      }
    }
  }

One more thing: Assuming you find yourself in the specific situation where every byte counts (maybe you are developing an app for extremely low bandwidth) it is technically possible to do the update that you are expecting manually using cache reads and writes. This is usually for the case when your mutation does not return everything that is updated. I would not recommend it for this case but it can be helpful for others reading this post and trying to get this behaviour explicitly.



来源:https://stackoverflow.com/questions/57250292/react-apollo-not-update-data-after-mutation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!