【发布时间】: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