Reactjs/Apollo/AppSync Mutation Optimistic Response Resolved



所以首先,我将首先说我对我的突变添加了乐观的反应,这样它就会停止产生这里和之前的 SO 问题中引用的重复项。

所以这一切都有效,但我有一组依赖突变,这些突变在第一次使用异步等待后运行。

  submitForm = async () => {
    // Only submit if form is complete
    if (!this.state.saveDisabled) {
      try {
        // Optimistic Response is necessary because of AWS AppSync
        // https://stackoverflow.com/a/48349020/2111538
        const createGuestData = await this.props.createGuest({
          name: this.state.name,
        })
        let guestId = createGuestData.data.addGuest.id
        for (let person of this.state.people) {
          await this.props.createPerson({
            variables: {
              name: person.name,
              guestId,
            },
            optimisticResponse: {
              addPerson: {
                id: -1, // A temporary id. The server decides the real id.
                name: person.name,
                guestId,
                __typename: 'Person',
              },
            },
          })
        }
        this.setState({
          redirect: true,
        })
      } catch (e) {
        console.log(e)
        alert('There was an error creating this guest')
      }
    } else {
      Alert('Please fill out guest form completely.')
    }
  }

现在这有效,并且它对突变使用与示例项目相同的模式

export default compose(
  graphql(CreateGuestMutation, {
    name: 'createGuest',
    options: {
      refetchQueries: [{ query: AllGuest }],
    },
    props: props => ({
      createGuest: guest => {
        console.log(guest)
        return props.createGuest({
          variables: guest,
          optimisticResponse: () => ({
            addGuest: {
              ...guest,
              id: uuid(),
              persons: [],
              __typename: 'Guest',
            },
          }),
        })
      },
    }),
  }),
  graphql(CreatePersonMutation, {
    name: 'createPerson',
  }),
)(CreateGuest)

唯一的问题是我无法强制状态更新为使用 Async Await 时实际插入的 ID,因此所有人员条目都会获得占位符 UUID。请注意,我也尝试使用id: -1就像对createPerson突变所做的那样,但这并没有改变任何东西,它只是对所有整体使用了负数。

有没有更好的方法?我做错了什么。这一切都在没有乐观反应的情况下起作用,但它总是为每个突变创建两个条目。

你能再试一次吗?适用于 Javascript 的 AppSync SDK 进行了增强,不再需要您使用乐观响应。如果仍需要乐观 UI,可以选择使用它。

此外,如果应用不需要离线,你现在还可以使用如下所示disableOffline来禁用脱机:

const client = new AWSAppSyncClient({
    url: AppSync.graphqlEndpoint,
    region: AppSync.region,
    auth: {
        type: AUTH_TYPE.API_KEY,
        apiKey: AppSync.apiKey,
    },
    disableOffline: true
});

相关内容

最新更新