Reactjs/Apollo/AppSync变异乐观响应已解析ID
首先我要说的是,我对我的突变增加了一个乐观的反应,这样它就不会像之前的S.O.那样产生重复 这一切都正常,但我有一组依赖突变,它们在第一次使用async await之后运行Reactjs/Apollo/AppSync变异乐观响应已解析ID,reactjs,graphql,react-apollo,aws-appsync,Reactjs,Graphql,React Apollo,Aws Appsync,首先我要说的是,我对我的突变增加了一个乐观的反应,这样它就不会像之前的S.O.那样产生重复 这一切都正常,但我有一组依赖突变,它们在第一次使用async await之后运行 submitForm = async () => { // Only submit if form is complete if (!this.state.saveDisabled) { try { // Optimistic Response is necessary
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 Wait时实际插入的ID,因此所有person条目都会获得占位符UUID。注意,我也尝试过使用id:-1
,就像使用createPerson突变一样,但这并没有改变任何事情,它只是对所有实体使用了负1
有更好的方法吗?我做错了什么事。这一切都在没有乐观反应的情况下起作用,但每次突变都会产生两个条目。你能再试一次吗?AppSync SDK for Javascript有一些增强功能,不再需要使用乐观响应。如果你仍然想要一个乐观的用户界面,你可以选择使用它 此外,如果应用程序不需要离线禁用,您现在还可以使用
disableOffline
禁用离线,如下所示:
const client = new AWSAppSyncClient({
url: AppSync.graphqlEndpoint,
region: AppSync.region,
auth: {
type: AUTH_TYPE.API_KEY,
apiKey: AppSync.apiKey,
},
disableOffline: true
});
你能再试一次吗?AppSync SDK for Javascript有一些增强功能,不再需要使用乐观响应。如果你仍然想要一个乐观的用户界面,你可以选择使用它 此外,如果应用程序不需要离线禁用,您现在还可以使用
disableOffline
禁用离线,如下所示:
const client = new AWSAppSyncClient({
url: AppSync.graphqlEndpoint,
region: AppSync.region,
auth: {
type: AUTH_TYPE.API_KEY,
apiKey: AppSync.apiKey,
},
disableOffline: true
});