用于删除和更新的React GraphQL订阅

时间:2018-01-23 07:17:55

标签: javascript reactjs graphql graphql-subscriptions

我尝试在API GraphQL Apollo中使用subscriptions,以便在React项目中实现更快,更实时的更新。我正在使用"subscriptions-transport-ws": "^0.8.2"。但是删除和更新会引发错误。我很反应和JS,并且无法完成这项工作。我试着寻找解决方案,但没有运气!

这是基本的前端布局: enter image description here

这里是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

enter image description here

更新按钮错误: Cannot assign to read only property 'Posts' of object '#<Object>'

enter image description here

有人可以帮我用graphql订阅来获取组件的实时更新吗?

1 个答案:

答案 0 :(得分:0)

您的问题与GraphQL或订阅无关!

更新

您正在尝试更改 React Props

previousResult.Posts = previousResult.Posts.map((p) => {...

previousResult 只读!

Del Post:

mainData.splice(post, 1)delPost的问题! splice更改变量,而mainData是常量!