Apollo Mutation-UI在useMutation更新后未更新

问题描述 投票:0回答:1

背景:始终能够使Apollo商店缓存更新,但没有UI

问题:

  1. 导致UI更新或未更新的原因是什么?
  2. 在更新中传递数据对象的正确方法是什么?

“反应”:“〜16.9.0”

“ @ apollo / react-hooks”:“ ^ 3.1.3”

UI和缓存更新的代码到我的项目中:

update: (store, { data: { newPhoto } }) => {
  const { bookInfo } = store.readQuery({ query: GET_BOOK_BY_ID, variables: { bookId } });
  bookInfo.photos = [...bookInfo.photos, newPhoto];

  store.writeQuery({ 
      query: GET_BOOK_BY_ID, 
      variables: { bookId },
      data: {
          bookInfo
      }
  });
}

在此行:bookInfo.photos = [...bookInfo.photos, newPhoto];中,bookInfo对象被直接修改,并刚刚传递回writeQuerydata

[这对我来说似乎不好,因为我看到人们说它必须是“不可变的”或“传递新对象”,等等。

reactjs apollo react-apollo
1个回答
0
投票

如果您遇到相同的事情,请检查以下列表:

  1. 去签出https://github.com/apollographql/apollo-client/pull/4543。通过将freezeResultsassumeImmutableResults应用于ApolloClient,将有助于发现问题。就我而言,问题实际上是在父组件内部发生的,该组件使Apollo存储对象发生了突变,而不是调用client.writeQuery的组件,我认为这通常也很难引起其他人的注意。
const client = new ApolloClient({
  link: ...,
  cache: new InMemoryCache({
    freezeResults: true, // new
  }),
  assumeImmutableResults: true, // new
});
  1. 确保您以不变的方式对数据进行变异。 (即,直到更新结束才更改Apollo商店对象)https://github.com/immerjs/immer绝对有助于使更改保持不变。我用它来突变嵌套对象,并且效果很好。
  2. 尝试使用从client返回的useMutation,然后您会得到client.writeQuery进行更新。尽管我不确定这一点,但仍有很多人在传播此信息,在某些情况下可能会有所帮助。
import { useMutation } from '@apollo/react-hooks';
import produce from "immer";

const [mutate, { client }] = useMutation(MUTATION_GQL);

const submit = () => {
    mutate({
        variables: { inputs },
        update: (store, { data: { response }) => {
            // get existing cache returned from the query
            const cache = store.readQuery({ query: QUERY_GQL, variables: { id } });

            // manipulate the cache in immutable fashion
            const data = produce(cache, draftCache => {
                draftCache.title = "new title";
                draftCache.approval = response;
            });

            // write the cache back to that query
            // REMEMBER the variables inside writeQuery too!
            client.writeQuery({
                query: QUERY_GQL,
                variables: { id },
                data,
            });
        }
    })
}
  1. 尝试使用useQuery而不是ApolloClient来读取readQuery中的数据,所以您将从Apollo的存储中获取更新的缓存
© www.soinside.com 2019 - 2024. All rights reserved.