React-Query:打字稿和抽象的用途?
我有一个小型应用程序,彼此之间有几种类似的数据。例如标签和状态的数据。因此,API也很相似。
现在,使用React-Query
,我正在写许多重复的突变。所有的突变(添加,更新,删除)都具有相同的结构:
export const useUpdateLabel = () => {
const queryClient = useQueryClient();
return useMutation(updateLabel, {
onSuccess: () => {
queryClient.invalidateQueries("labels");
console.log(`Updated`);
},
onError: (error) => {
process.env.NODE_ENV !== "production" && console.error(error);
},
});
};
我正在使用自定义钩子使代码清洁器,但是有什么方法可以减少重复代码?
我可以做类似的事情:
export const useCustomMutation = (func, key) => {
const queryClient = useQueryClient();
return useMutation(func, {
onSuccess: () => {
queryClient.invalidateQueries(key);
console.log(`Updated`);
},
onError: (error) => {
process.env.NODE_ENV !== "production" && console.error(error);
},
});
};
但是不知道如何正确制作类型。
I have a small app with several kinds of data similar with each other. For example data for labels and statuses. And so the apis are similar too.
Now with react-query
, I'm writing many repetitive mutations. All the mutations (add, update, delete) have same structure:
export const useUpdateLabel = () => {
const queryClient = useQueryClient();
return useMutation(updateLabel, {
onSuccess: () => {
queryClient.invalidateQueries("labels");
console.log(`Updated`);
},
onError: (error) => {
process.env.NODE_ENV !== "production" && console.error(error);
},
});
};
I'm using custom hooks to make the code cleaner, but is there any way to reduce the repetitive codes?
I can do something like:
export const useCustomMutation = (func, key) => {
const queryClient = useQueryClient();
return useMutation(func, {
onSuccess: () => {
queryClient.invalidateQueries(key);
console.log(`Updated`);
},
onError: (error) => {
process.env.NODE_ENV !== "production" && console.error(error);
},
});
};
but have no idea how to make the types right.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
this should work nicely:
this should work nicely:
link to typescript playground