redux 我是否应该将try catch块封装在for循环RTK查询中?

dm7nw8vv  于 2023-01-21  发布在  其他
关注(0)|答案(1)|浏览(90)

我使用rtk查询并制作乐观UI。因此我通过端点进行选择并更改数据,但有一件事。我在for循环中有一个常量变量“patchResult”,在for循环外部我等待查询完成。因此我无法patchResult.undo(),因为patchResult变量在for循环内部,而我的try catch块在for循环外部,所以我无法访问该变量。我应该把try catch块放在for循环中还是它不好?

async onQueryStarted({ user_id }, { dispatch, queryFulfilled, getState }) {
         for (const { endpointName, originalArgs } of Api.util.selectInvalidatedBy(getState(), [{ type: 'USER'}])) { 
          
          const patchResult = dispatch(
            UserApi.util.updateQueryData('users', originalArgs, (draft) => {
              return {
                ...draft,
                user: {
                  ...draft.user,
                  is_follow: !draft.user.is_follow
                }
              }
            })
          );
        }

       try {
          await queryFulfilled
        } catch {
          patchResult.undo();
        }
moiiocjp

moiiocjp1#

您可能需要一系列修补程序:

async function onQueryStarted(
  { user_id },
  { dispatch, queryFulfilled, getState }
) {
  let allPatches = [];

  for (const { endpointName, originalArgs } of Api.util.selectInvalidatedBy(
    getState(),
    [{ type: "USER" }]
  )) {
    const patchResult = dispatch(
      UserApi.util.updateQueryData("users", originalArgs, (draft) => {
        return {
          ...draft,
          user: {
            ...draft.user,
            is_follow: !draft.user.is_follow,
          },
        };
      })
    );

    allPatches.push(patchResult);
  }

  try {
    await queryFulfilled;
  } catch {
    for (const patchResult of allPatches) {
      patchResult.undo();
    }
  }
}

相关问题