-
BackgroundEDIT: I should probably mention I'm using react-beautiful-dnd for the UI. Not sure if relevant at all but 🤷♀️ const todoItems = [
{
id: 1,
label: "Do laundry"
},
{
id: 2,
label: "Fix bug"
},
] When a user reorders the list; I have a function that runs in const reorder = <T,>(list: T[], startIndex: number, endIndex: number) => {
const result = Array.from(list);
const [removed] = result.splice(startIndex, 1);
result.splice(endIndex, 0, removed);
return result;
}; then calls Then, I have the (async) function that I pass in The thing is, in the async function that I pass in ...
const previousTodos = queryClient.getQueryData<ITodo[]>("todos")
... The problem is that since Shouldn't the functions in Whole pseudo code const reorderTodo = useMutation(
async ({ source, destination }: IReorderData) => {
const previousTodos = queryClient.getQueryData<ITodo[]>("todos"); // I'm getting the already reordered todos here when I really need the unreordered one
try {
/* workaround for now (see last section)
queryClient.setQueryData(
"todos",
reorder(previousTodos, source, destination)
);
*/
// some logic here to update the single item that was reordered ...
await updateDatabase(...)
} catch (error) {
throw error;
}
},
{
onMutate: ({ source, destination }: IReorderData) => {
const previousTodos = queryClient.getQueryData<ITodo[]>("todos");
queryClient.setQueryData(
"todos",
reorder(previousTodos, source, destination)
); // this sets the query data that is gotten by the previous function passed in useMutation 😢
return { previousTodos };
},
onError: (_error, _, context) => {
queryClient.setQueryData(
"todos",
context.previousTodos
);
},
}
); Current workaroundWhat I'm doing now is instead of calling the synchronous reorder function in |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
as you've already found out - |
Beta Was this translation helpful? Give feedback.
as you've already found out -
onMutate
runs before themutateFn
. Both functions are not "receiving" any data - you are reading them from the cache. so if the function that runs first writes data to the cache, I think it's okay that if the function that runs after that will get the latest value if it reads it from that cache.