For reference, this is what I've been trying to accomplish: https://hasura.io/learn/graphql/react-native/update-delete-mutations/4-remove-todos-integration/
I've been stuck trying to figure out how to solve this problem. I have a page with a list of blog posts and each post has a delete button that gets rendered within it.
const renderBlogs = (blogs) => {
return data.blogs.map(({ id, title, body }) => (
<ListItem key={id}>
<div>
<div>
<h3>
<Link to={`/blog/${id}`}>{title}</Link>
</h3>
<div>
<Button
onClick={(e) => {
e.preventDefault();
let result = window.confirm(
'Are you sure you want to delete?',
);
if (result) {
deleteBlog({
variables: { id },
update: updateCache,
});
history.push('/blog');
}
}}
>
Delete
</Button>
</div>
</div>
<p>{body}</p>
</div>
</ListItem>
));
Each of these li's get rendered out with:
<List>{renderBlogs(data.blogs)}</List>
When the delete button is clicked, it calls the deleteBlog function from const [deleteBlog] = useMutation(DELETE_BLOG);
which successfully deletes the blog. So far so good. Now the problem is trying to update the cache so the page doesn't need to be refreshed to show the changes. Here is my updateCache function which does not work properly:
const updateCache = (client) => {
data.blogs.map(({ id, title, body }) => {
const data = client.readQuery({
query: FETCH_BLOGS,
variables: {
title,
body,
},
});
const newData = {
blogs: data.blogs.filter((t) => t.id !== id),
};
client.writeQuery({
query: FETCH_BLOGS,
variables: {
title,
body,
},
data: newData,
});
return newData;
});
};
When the delete button is clicked, it deletes ALL of the blogs in the cache (something to do with using .map()) but upon refreshing the page, only the blog that was actually deleted is gone (as desired).
I know there is some error in my logic withing updateCache() but I'm not sure how to fix it. Any help is appreciated. Thanks.