🔮 Optimistic Response in Apollo Client
Optimistic response is a way to update the UI before the server responds. This is useful when you want to give the user a feeling of instant feedback. For example, when you want to update the UI before the server responds with the updated data.
In ApolloClient, you can use the optimisticResponse
option to update the UI before the server responds. This option is available in the useMutation
hook.
📝 Example
Let's say we have a Todo
type with a completed
field. We want to update the UI before the server responds with the updated data.
type Todo { id: ID! title: String! completed: Boolean! }
type Todo { id: ID! title: String! completed: Boolean! }
We can use the optimisticResponse
option to update the UI before the server responds with the updated data.
const [updateTodo] = useMutation(UPDATE_TODO, { optimisticResponse: { __typename: 'Mutation', updateTodo: { __typename: 'Todo', id: todo.id, completed: !todo.completed, }, } });
const [updateTodo] = useMutation(UPDATE_TODO, { optimisticResponse: { __typename: 'Mutation', updateTodo: { __typename: 'Todo', id: todo.id, completed: !todo.completed, }, } });
Once we have our optimisticResponse
, we can use it to update the UI before the server responds with the updated data.
const handleToggle = () => { updateTodo({ variables: { id: todo.id, completed: !todo.completed, }, }); };
const handleToggle = () => { updateTodo({ variables: { id: todo.id, completed: !todo.completed, }, }); };