Apollo useQuery挂钩无法通过writeQuery()方法从缓存中获取更新。没有看到错误

时间:2019-10-02 17:10:58

标签: javascript reactjs graphql apollo

使用useMutation()后,缓存会更新,但Home组件中的useQuery()不会更新。

我尝试使用其他fetchPolicy。我可以在Apollo开发工具中看到新帖子,但需要更新页面以查看更改

import { FETCH_POSTS_QUERY } from '../utils/graphql';

function Home() {
  const { user } = useContext(AuthContext);
  const {
    loading,
    data
  } = useQuery(FETCH_POSTS_QUERY, {
    fetchPolicy: 'cache-and-network',
  });
...

import { useMutation } from '@apollo/react-hooks';

import { useForm } from '../utils/hooks';
import { FETCH_POSTS_QUERY } from '../utils/graphql';

function PostForm() {
  const { values, onChange, onSubmit } = useForm(createPostCallback, {
    body: ''
  });

  const [createPost, { error }] = useMutation(CREATE_POST_MUTATION, {
    variables: values,
    update(proxy, result) {
      const data = proxy.readQuery({
        query: FETCH_POSTS_QUERY
      });
      data.getPosts.push(result.data.createPost);
      proxy.writeQuery({ query: FETCH_POSTS_QUERY, data });
      values.body = '';
    }
  });

  function createPostCallback() {
    createPost();
  }
...
...
import { InMemoryCache } from 'apollo-cache-inmemory';
import { createHttpLink } from 'apollo-link-http';
import { ApolloProvider } from '@apollo/react-hooks';
import { setContext } from 'apollo-link-context';

const httpLink = createHttpLink({
  uri: 'http://localhost:5000'
});

const authLink = setContext(() => {
  const token = localStorage.getItem('jwttoken');
  return {
    headers: {
      Authorization: token ? `Bearer ${token}` : ''
    }
  };
});

const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache()
});

...

我希望看到新帖子而不更新页面。

2 个答案:

答案 0 :(得分:1)

您在此处使用push修改缓存的数据:

data.getPosts.push(result.data.createPost);

然后按原样返回

proxy.writeQuery({ query: FETCH_POSTS_QUERY, data });

因为这是JavaScript,并且对象是通过引用传递的,所以您返回的data与您收到的对象是同一对象,因此apollo并未意识到它已更改。请尝试以下操作:

proxy.writeQuery({ query: FETCH_POSTS_QUERY, data: { ...data } });

答案 1 :(得分:1)

此代码段解决了使用PostForm编写缓存时前端刷新的问题:

//在Home.js中使用以下代码:

const [posts, setPosts] = useState([]);
const { user } = useContext(AuthContext);
const { loading, data } = useQuery(FETCH_POSTS_QUERY);
useEffect(() => {
    if (data) {
        setPosts(data.getPosts);
    }
}, [data]);

在PostForm.js中使用以下代码:

const [createPost, { error }] = useMutation(CREATE_POST_MUTATION, {
    variables: values,
    update(proxy, result) {
        const data = proxy.readQuery({
            query: FETCH_POSTS_QUERY
        });
        const new_post = result.data.createPost;
        proxy.writeQuery({
            query: FETCH_POSTS_QUERY,
            data: { getPosts: [new_post, ...data.getPosts] }
        });
        values.body = '';
    }
});

这个解决方案不是我的主意,但是一位代码英雄可以帮助我们:)

参考链接:https://gist.github.com/josuecatalan/5b8bf73e69d55683ccf237d5d02b5cef

原始内容: https://www.youtube.com/watch?v=F_SdB42DxdQ&list=PLMhAeHCz8S3_pgb-j51QnCEhXNj5oyl8n&index=6