每次我在我的应用程序中添加一个新项目时,由于某种原因,突变会调用update()
四次。前两个是乐观数据,第二批,一个是乐观数据,一个是来自网络的真实数据。我无法理解这一点。正在创建的新项目在页面上显示两次。
这是我的突变:
mutation CreateTrack($name: String!, $trackNum: Int, $s3Key: String!) {
createTrack(name: $name, trackNum: $trackNum, s3Key: $s3Key) {
trackId
name
createdAt
duration
trackNum
s3Key
isProcessing
didProcessingFail
}
}
这是突变代码:
createTrack({ name, s3Key }) {
const newTrack = {
name,
s3Key,
};
this.$apollo
.mutate({
mutation: createTrackMutation,
variables: newTrack,
update: (store, { data: { createTrack } }) => {
console.log('this is dumb', JSON.stringify(createTrack, null, 2));
const variables = {
limit: this.pageSize,
order: this.order === 'ascending' ? 'asc' : 'desc',
sortBy: this.sortBy,
};
const data = store.readQuery({
query: listTracksQuery,
variables,
});
data.listTracks.items.push(createTrack);
store.writeQuery({
query: listTracksQuery,
variables,
data,
});
},
optimisticResponse: {
__typename: 'Mutation',
createTrack: {
__typename: 'Track',
...newTrack,
trackId: '??',
createdAt: new Date().toISOString(),
isProcessing: true,
didProcessingFail: false,
duration: null,
trackNum: 999,
},
},
})
.then(data => {
console.log('done!', data);
})
.catch(err => {
console.log('error', err);
});
},
最后,这里是调用 mutate一次的控制台日志:
this is dumb {
"__typename": "Track",
"name": "small2.wav",
"s3Key": "staging/audio/10e3e675-e7a6-41dc-a8fb-686ad683e40e.wav",
"trackId": "??",
"createdAt": "2018-03-05T03:30:18.246Z",
"isProcessing": true,
"didProcessingFail": false,
"duration": null,
"trackNum": 999
}
this is dumb {
"__typename": "Track",
"name": "small2.wav",
"s3Key": "staging/audio/10e3e675-e7a6-41dc-a8fb-686ad683e40e.wav",
"trackId": "??",
"createdAt": "2018-03-05T03:30:18.246Z",
"isProcessing": true,
"didProcessingFail": false,
"duration": null,
"trackNum": 999
}
done! {data: {...}}
this is dumb {
"__typename": "Track",
"name": "small2.wav",
"s3Key": "staging/audio/10e3e675-e7a6-41dc-a8fb-686ad683e40e.wav",
"trackId": "??",
"createdAt": "2018-03-05T03:30:18.246Z",
"isProcessing": true,
"didProcessingFail": false,
"duration": null,
"trackNum": 999
}
this is dumb {
"trackId": "2b3de8ac-d145-4da6-b522-27e5413d43e1",
"name": "small2.wav",
"createdAt": "2018-03-05T03:30:18.627Z",
"duration": null,
"trackNum": 999,
"s3Key": "staging/audio/10e3e675-e7a6-41dc-a8fb-686ad683e40e.wav",
"isProcessing": true,
"didProcessingFail": null,
"__typename": "Track"
}
我在这里做错了什么?