In an optimistic update the UI behaves as though a change was successfully completed before receiving confirmation from the server that it actually was - it is being optimistic that it will eventually get the confirmation rather than an error. This allows for a more responsive user experience.
export const useEditProject = () => { const queryClient = useQueryClient(); const [searchParams] = useProjectsSearchParam(); // queryKey,缓存中的key const queryKey = ["projects", searchParams]; return useMutation( // variables is an object that mutate will pass to your mutationFn, mutate其实就是把参数传给这个函数,然后触发它 async (params: Partial<Project>) => { const res = await editProject(params); return res.data; }, { onSuccess: () => queryClient.invalidateQueries(queryKey), // This function will fire before the mutation function is fired and is passed the same variables the mutation function would receive // 在mutate完成前触发,接受和mutate一样的参数 // 实现乐观更新,在异步请求完成之前,先将改变发生,若发生了错误再回滚 async onMutate(target: Partial<Project>) { const previousItems = queryClient.getQueryData(queryKey); queryClient.setQueryData(queryKey, (old?: Project[]) => { const newV = old?.map((project) => project.id === target.id ? { ...project, ...target } : project ) || []; return newV; }); return { previousItems }; }, // This function will fire if the mutation encounters an error and will be passed the error. // If a promise is returned, it will be awaited and resolved before proceeding onError(error: Error, newItems: Partial<Project>, context: any) { // 回滚 queryClient.setQueryData(["projects", param], context.previousItems); }, } ); };