const addNewHabit = async ({ userId, habitName, getFullYear }) => {
try {
const { data } = await axios.post(import.meta.env.VITE_API_URL, {
userId,
habitName,
getFullYear,
});
return data._id;
} catch (error) {
console.log(error.message);
}
};
export const addHabitData = () => {
const queryClient = useQueryClient();
return useMutation(addNewHabit, {
onMutate: async (newHabit) => {
await queryClient.cancelQueries("habits");
const previousHabitsData = queryClient.getQueryData("habits");
const id = await addNewHabit(newHabit);
queryClient.setQueryData("habits", (oldQueryData) => {
return [...oldQueryData, { ...newHabit, _id: id }];
});
return { previousHabitsData };
},
onError: (_error, __habit, context) => {
queryClient.setQueriesData("habits", context.previousHabitsData);
},
onSettled: () => {
queryClient.invalidateQueries("habits");
},
});
};
I am trying to get _id from the mongodb for implementing the dynamic route for details page. When deal with optimistic update, I don't get Id generate by mongodb which cause my page /undefined because it take some time to re-fetching by react-query. My current implement works, but it created twice. Are there any other approach?