gpt4 book ai didi

javascript - Apollo useQuery Hook 无法使用 writeQuery() 方法从缓存获取更新。没有看到错误

转载 作者:行者123 更新时间:2023-12-03 14:17:00 25 4
gpt4 key购买 nike

使用 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()
});

...

我希望在不更新页面的情况下看到新帖子。

最佳答案

这段代码解决了用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

关于javascript - Apollo useQuery Hook 无法使用 writeQuery() 方法从缓存获取更新。没有看到错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58206190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com