Hello!
I’ve been implementing Apollo graph for the last few months and i am really impressed with how easy and well documented everything is. Except for the optimistic response part.
This is the documentation from Apollo:
// Mutation definition
const UPDATE_COMMENT = gql`
mutation UpdateComment($commentId: ID!, $commentContent: String!) {
updateComment(commentId: $commentId, content: $commentContent) {
id
__typename
content
}
}
`;
// Component definition
function CommentPageWithData() {
const [mutate] = useMutation(UPDATE_COMMENT);
return (
<Comment
updateComment={({ commentId, commentContent }) =>
mutate({
variables: { commentId, commentContent },
optimisticResponse: {
updateComment: {
id: commentId,
__typename: "Comment",
content: commentContent
}
}
})
}
/>
);
}
It seems easy enough. But it doesn’t work, as far as i know.
You have to go into their sandbox example to understand that there’s more to it. Or search medium or something else to understand that there’s alot more to the optimistic response then the docs tell you initially.
This is as close to the truth about optimistic ui as i can understand. The FULL documentation.
try {
await createTodo({
variables: {
input: {
title,
completed: false
}
},
// Provide a fake response of the mutation response
optimisticResponse: {
createTodo: {
__typename: 'Todo',
title,
completed: false
}
},
/* Update Apollo cache based on the responses
* This callback function will be fired two times
* 1. Before the API request starts to update the cache
* with the fake response we provide in `optimisticResponse`
* 2. After the API request resolves to update the cache
* with the actual response from the server
*/
update: (proxy, response) => {
// Read the data from our cache for this query.
const previousData = proxy.readQuery({ query: GET_TODOS })
// Write our data back to the cache with the new todo in it
proxy.writeQuery({
query: GET_TODOS,
data: {
...previousData,
todos: [
response.data.createTodo,
...previousData.todos,
]
}
})
},
// Refetch queries after mutation finishes successfully
refetchQueries: [
{
query: GET_TODOS
}
],
// Wait for the refetched queries to be completed, before resolving the mutation
awaitRefetchQueries: true
})
} catch (error) {
console.log(error)
}
So my question is if i have understood the documentation on Apollo and other sources correctly? Do i really have to manage the local cache manually by myself, as the last example implies, in order to get the optimistic behavior to work? Or is it something with the Apollo docs that i’m missing?
The idea of Optimistic is so simple in the docs, and when you start investigating it, it’s really extensive for each mutation. It seems strange and out of context with Apollo that has been really easy to understand up to this point.
Hoping for some clarification from more senior Apollo developers then myself!
All the best,
Axel