【问题标题】:Reactjs/Apollo/AppSync Mutation Optimistic Response Resolved IDReactjs/Apollo/AppSync Mutation Optimistic Response Resolved ID
【发布时间】:2018-07-09 18:57:09
【问题描述】:

所以首先我会说我对我的突变添加了一个乐观的响应,所以它会停止产生重复,如引用 here 和之前的 S.O. question.

这一切正常,但我有一组依赖突变在第一次使用 async await 之后运行。

  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)

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

有没有更好的方法来做到这一点?我做错了什么。这一切都在没有optimisticResponse 的情况下工作,但它总是为每个突变创建两个条目。

【问题讨论】:

    标签: reactjs graphql react-apollo aws-appsync


    【解决方案1】:

    你能再试一次吗? AppSync SDK for Javascript 的增强功能不再需要您使用乐观响应。如果您仍然想要一个乐观的 UI,您可以选择使用它。

    此外,如果您的应用不需要离线,您现在还可以使用 disableOffline 来禁用离线功能,如下所示:

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

    【讨论】:

      猜你喜欢
      • 2018-06-28
      • 2018-11-09
      • 2019-02-25
      • 2019-05-04
      • 2019-03-12
      • 2019-06-12
      • 2019-02-20
      • 2018-09-24
      • 2018-05-27
      相关资源
      最近更新 更多