我一直在useMutation()
为我的应用程序使用 crud 任务的钩子,我觉得我在写很多重复的代码,最初我的代码是这样的:
const [createList] = useCreateList(reset, err => setError(err.message));
const [updateList] = useCreateList(reset, err => setError(err.message));
const [deleteList] = useCreateList(reset, err => setError(err.message));
重置功能是这样的:
const reset = () => {
setQsButtonStatus(null);
setSelectedList(null);
setTitleValue("");
}
我想要的所需结束代码是这样的:
const {createList, updateList, deleteList} = useListMutation(reset, err => setError(err.message))
我可以完成这项工作,但对我来说,它的代码看起来很乱(同样有很多重复的代码):
import * as List from "./list-api";
const useListMutation = (onSettled, onError) => {
const [createList] = useMutation(List.createList, {
onMutate: (listTitle) => {
queryCache.cancelQueries("lists");
const current = queryCache.getQueryData("lists");
queryCache.setQueryData("lists", prev => [...prev, {title: listTitle, id: uuidv4()}])
return () => queryCache.setQueryData("lists", current);
},
onError: (err, variables, rollback) => {rollback(); onError(err)},
onSettled: () => {
queryCache.invalidateQueries("lists");
onSettled();
}
})
const [updateList] = useMutation(List.updateList, {
onMutate: ({id, titleValue}) => {
queryCache.cancelQueries("lists");
const current = queryCache.getQueryData("lists");
queryCache.setQueryData("lists", prev => [
...prev.filter(list => list._id !== id),
{_id: id, title: titleValue}
])
return () => queryCache.setQueryData("lists", current);
},
onError: (err, variables, rollback) => {rollback(); onError(err)},
onSettled: () => {
queryCache.invalidateQueries("lists");
onSettled();
}
})
const [deleteList] = useMutation(List.deleteList, {
onMutate: (id) => {
queryCache.cancelQueries("lists");
const current = queryCache.getQueryData("lists");
queryCache.setQueryData("lists", prev => [
...prev.filter(list => list._id !== id),
])
return () => queryCache.setQueryData("lists", current);
},
onError: (err, variables, rollback) => {rollback(); onError(err)},
onSettled: () => {
queryCache.invalidateQueries("lists");
onSettled();
}
})
return {createList, updateList, deleteList};
}
export default useListMutation;
有一个更好的方法吗?