After using useMutation()
, cache gets updated but useQuery()
in Home component doesn't.
I tried with a different fetchPolicy
. I can see new posts in Apollo dev tool but the page needs to be updated to see the changes
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()
});
...
I expect seeing the new post without updating the page.