微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我们如何在 RTK 查询中重置突变的数据和状态,例如 React Query 中的重置函数进行突变?

如何解决我们如何在 RTK 查询中重置突变的数据和状态,例如 React Query 中的重置函数进行突变?

我在 React 项目中使用带有 Redux Tool kit 的 RTK 查询。表行使用 RTK 突变提供的“updateProductCategory”函数更新。但是在每个表行更新后,“updateProductCategoryResult”填充了该更新行的数据和状态(也就是说,如果更新成功,则“isSuccess”=true)。

因此对于下一次更新,由于 "isSuccess" 突变状态为 "true" ,当打开要编辑行的模式表单时(在实际编辑发生之前),SnackBar(即烤面包机)将弹出。因此,为了避免弹出这种不需要的 Snack Bar,我想在突变发生后重置突变结果的数据和状态,即"updateProductCategoryResult" 使 isSuccess = false,isError = false 。

基本上我需要像 React Query 突变一样的 reset() 函数

搜索了 RTK 查询文档,但没有找到任何与突变状态和数据重置相关的内容

代码

//State to open SnackBar
const [snackBarProps,setSnackBarProps] = useState({
    alertType: "",message: "",});

// Hooks to fetch product category
const { data = [],isFetching } = useGetProductCategoryQuery(queryBody);

//Hook to update product category
const [updateProductCategory,updateProductCategoryResult] = useUpdateProductCategoryMutation();

// SnackBar while "Updating Category".
// Bug occured here,as "updateProductCategoryResult.isSuccess" will be  
// true after every successful update,which changes the "snackBarProps" 
// state by calling "setSnackBarProps" and pops the Snack Bar when just 
// opening the modal to edit row data of the table.

  useEffect(() => {
    if (updateProductCategoryResult.isError) {
      setSnackBarProps({
        alertType: "error",message: "Updating Product Category Failed !!!",});
    }

    if (updateProductCategoryResult.isSuccess) {
      setSnackBarProps({
        alertType: "success",message: "Updated Product Category Successfully !!!",});

      dispatch(closeModal());
    }

    return () => {
      setSnackBarProps({
        alertType: "",});
    };
  },[updateProductCategoryResult,isFetching]);

解决方法

只需使用不同的依赖数组 - 现在它会在 updateProductCategoryResult 的每次更改时触发 - 但您希望它在 isErrorisSuccess 更改时触发:

 [updateProductCategoryResult.isError,updateProductCategoryResult.isSuccess,isFetching]);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。