我尝试在API GraphQL Apollo
中使用subscriptions
,以便在React
项目中实现更快,更实时的更新。我正在使用"subscriptions-transport-ws": "^0.8.2"
。但是删除和更新会引发错误。我很反应和JS,并且无法完成这项工作。我试着寻找解决方案,但没有运气!
这里是graphql subscriptions
的相关反应组件代码:
componentWillReceiveProps(nextProps) {
if (!this.subscription && !nextProps.data.loading) {
let { subscribeToMore } = this.props.data
this.subscription = [subscribeToMore(
{
document: postDeleted,
updateQuery: (previousResult, { subscriptionData }) => {
const delPost = subscriptionData.data.postDeleted;
const mainData = previousResult.Posts;
let post = mainData.find(post => post.id == delPost.id);
let updatedList = mainData.splice(post, 1);
return updatedList;
},
}),
subscribeToMore(
{
document: postUpdated,
updateQuery: (previousResult, { subscriptionData }) => {
previousResult.Posts = previousResult.Posts.map((p) => {
if(p.id === subscriptionData.data.postEdited.id) {
return subscriptionData.data.postEdited
} else {
return p;
}
});
return previousResult;
},
}
)]
}
}
但我面临以下错误:
删除按钮错误:
TypeError: Cannot add/remove sealed array elements
更新按钮错误:
Cannot assign to read only property 'Posts' of object '#<Object>'
有人可以帮我用graphql订阅来获取组件的实时更新吗?
答案 0 :(得分:0)
您的问题与GraphQL或订阅无关!
更新
您正在尝试更改 React Props !
previousResult.Posts = previousResult.Posts.map((p) => {...
但 previousResult 只读!
Del Post:
mainData.splice(post, 1)
是delPost
的问题!
splice
更改变量,而mainData
是常量!