I try to use optimistic ui pattern with graphql-codegen but it is not working with subscription.
I have a chat application and i paste the mutation schema and the subscription.
I am using the hooks that graphql-codegen generated.
subscription LiveMessagesList($chatId: uuid!, $order: order_by) {
message(
where: { chat_id: { _eq: $chatId } }
order_by: { created_at: $order }
) {
id
chat_id
sender {
id
displayName
avatarUrl
}
content
created_at
is_seen
}
}
}
mutation InsertNewMessage($chatId: uuid!, $content: String!) {
insert_message(objects: [{ chat_id: $chatId, content: $content }]) {
affected_rows
returning {
id
chat_id
sender {
id
displayName
avatarUrl
}
content
created_at
is_seen
}
}
}
When the user sent the message i want to immediately update the messages, if the network is slow the message is appearing slowly, this is why i would like to use this optimistic ui method.
I searched the documentaion on apollo and i developd almost the same but it isnt working and i dont know why.
this is my code in my MessageInput component in React it is called on user event:
const onSubmit: SubmitHandler<SignInFormValues> = async ({ message }) => {
if (!message) {
return;
}
const optimisticMessage = {
__typename: "message",
id: "temp-id",
chat_id: chat_id,
sender: {
__typename: "users",
id: user?.id,
displayName: user?.displayName,
avatarUrl: user?.avatarUrl,
},
content: message,
created_at: new Date().toISOString(),
is_seen: false,
};
insertNewMessageMutation({
variables: {
chatId: chat_id,
content: message,
},
optimisticResponse: {
insert_message: {
__typename: "message_mutation_response",
affected_rows: 1,
returning: [optimisticMessage],
},
},
update: (cache, { data }) => {
const newMessage = data?.insert_message?.returning?.[0];
if (!newMessage) return;
cache.modify({
fields: {
message(existingMessages = []) {
const newMessageRef = cache.writeFragment({
data: newMessage,
fragment: gql`
fragment NewMessage on message {
id
chat_id
sender {
id
displayName
avatarUrl
}
content
created_at
is_seen
}
`,
});
return [...existingMessages, newMessageRef];
},
},
});
},
});
};
This is the Messages component where the subscription gets the live messages array from database.
const { data, loading, error } = useLiveMessagesListSubscription({
variables: {
chatId: chat_id,
order: "asc",
},
});
Data contains the messages array and i render it to the user.
What am I missing here?
I am a little bit confused how to use it, this code is from the documentation for optimistic ui. I couldn’t find for subscription so i changed that from query. I hope it is working with subscription too. Because need the live messages. I am would like to achive if the user hits the submit button the messages array immediately changes.