在 RTK 查询中撤消操作以进行乐观更新

问题描述 投票:0回答:0

我正在使用带有 Redux 工具包和 RTK 查询的 React。对于乐观更新,我需要撤消任何已派发的操作的可能性。 RTK 查询允许在调度结果上使用

undo()
方法。

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'

const api = createApi({
  endpoints: (build) => ({

    // Action for getting the list of all items.
    getItems: build.query({ query: () => 'items' }),

    // Action for adding new item.
    addItem: build.mutation({
      query: (body) => ({ url: 'item', method: 'POST', body }),
      onQueryStarted({ id, ...body }, { dispatch, queryFulfilled }) {
        const patch = dispatch(api.util.updateQueryData('getItems', undefined, (items) => [...items, body]))
        queryFulfillled.catch(patch.undo) // On fail, undo the action (so remove the added item)
      }
    })
  })
})

但是,问题是当我有一个项目数组时,某些操作会向其中添加新项目。我怎样才能恢复它?

undo
方法只是将数组设置为调度操作之前的状态。但是,如果我同时多次发送 action 怎么办?所有项目都将被删除,即使只有 1 个失败。

// items: []
dispatch(addItem({ id: '1' }))
// items: [{ id: '1' }]
dispatch(addItem({ id: '2' }))
// items: [{ id: '1' }, { id: '2' }]
// Now, first dispatch asynchronously fail, so undo the first action
// items: [], but should be [{ id: '2' }]

当然我可以自己make undo,手动修改item列表。但是有什么方法可以自动执行数组的撤消操作吗?如果添加某些项目失败,仅撤消(删除)此项目,而不是其他项目。

reactjs redux redux-toolkit rtk-query undo-redo
© www.soinside.com 2019 - 2024. All rights reserved.