T
TanStack3y ago
passive-yellow

Optimistic update when the request and response type are different

Let's say I have a task list. I use 2 apis - 1. getTask which gives a response of the type
type TaskData = {
_id: ObjectId,
title: string,
tasker: {
_id: ObjectId,
name: string,
email: string
}
}
type TaskData = {
_id: ObjectId,
title: string,
tasker: {
_id: ObjectId,
name: string,
email: string
}
}
2. updateTask which has a request of the type
type TaskRequest = {
_id: ObjectId,
title?: string;
taskerId?: ObjectId
}
type TaskRequest = {
_id: ObjectId,
title?: string;
taskerId?: ObjectId
}
Let's say I am updating the tasker for a task. My request for the updateTask is of type TaskRequest
{
_id: ObjectId,
taskerId: ObjectIdd,
}
{
_id: ObjectId,
taskerId: ObjectIdd,
}
However, to make an optimistic update, I need to locally replace an object of the type TaskData. How should I do this? Should my mutation take in 2 params (request for the api and an object of type TaskData for the optimistic update)?
5 Replies
harsh-harlequin
harsh-harlequin3y ago
It looks like you might be lacking the information required to perform a complete optimistic update. If you're only receiving partial data in response from the mutation, and that partial data isn't enough to perform the optimistic update, and you don't have the desired data in state locally then I think you might want to revisit your API contract
stormy-gold
stormy-gold3y ago
You only send taskerId to updateTask, but when the user selects that new taskerId, don't they see the info (name + email) about that new taskerId they are selecting? If so, you could use that data with setQueryData.
passive-yellow
passive-yellowOP3y ago
Sorry I wasn't clear enough. As @julien mentioned, I do have the info (name + email) since the user needs to see that. Does it make sense then that the mutation takes in 2 parameters - 1. The request for the updateTask api and 2. The data for the optimistic update?
harsh-harlequin
harsh-harlequin3y ago
It's impossible to say without seeing any code but it's possible that your mutation function onSuccess function closes over those values which you could use to make the update
passive-yellow
passive-yellowOP3y ago
I think I will make another post with all the code + data clearly outlined Sorry for the confusion!

Did you find this page helpful?