Skip to content

Instantly share code, notes, and snippets.

@josuerodcat90
Created October 15, 2019 00:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josuerodcat90/5b8bf73e69d55683ccf237d5d02b5cef to your computer and use it in GitHub Desktop.
Save josuerodcat90/5b8bf73e69d55683ccf237d5d02b5cef to your computer and use it in GitHub Desktop.
//this code snippet solve the problem with frontend refresh when you write the cache with PostForm:
//in Home.js use this:
const [posts, setPosts] = useState([]);
const { user } = useContext(AuthContext);
const { loading, data } = useQuery(FETCH_POSTS_QUERY);
useEffect(() => {
if (data) {
setPosts(data.getPosts);
}
}, [data]);
//and in PostForm.js use this:
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 = '';
}
});
//this solution was not my idea, but one code hero help us :)
@enestatli
Copy link

Thank you!

@josuerodcat90
Copy link
Author

Thank you!

you're welcome!

@enspdf
Copy link

enspdf commented Jan 12, 2020

Thx

@mortub
Copy link

mortub commented Jan 18, 2020

thank you!

@terrygreen0606
Copy link

Really Helpful. Thank you very much.
I was struggling with google to solve this and finally got the answer here.

@ivonakov
Copy link

Thank you!

@lightmnd
Copy link

lightmnd commented Mar 15, 2020

to resolve the updating UI issue, try to add this inside your useMutation function
refetchQueries: refetchPosts => [{query: FETCH_POSTS_QUERY}]
hope it's helpful! ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment