0

I'm trying to use GraphQL Apollo in API subscriptions for faster and realtime updates in my React Project. I'm using "subscriptions-transport-ws": "^0.8.2". But delete and update is throwing error. I'm quite new to react and JS and am not able to get this work. I tried searching for a solution but no luck yet!

Here's the basic front-end layout: enter image description here

And here's the related react component code for 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;
                    },
                }
                )]
        }
    }

But I'm facing following errors:

Delete Button Error: TypeError: Cannot add/remove sealed array elements

enter image description here

And Update Button Error: Cannot assign to read only property 'Posts' of object '#<Object>'

enter image description here

Can someone please help me get realtime updates in the component with graphql subscriptions?

s develop
  • 115
  • 3
  • 16

1 Answers1

0

Your issue is not related to GraphQL or Subscriptions!

Update:

You are trying to change React Props!

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

but previousResult is readonly!

Del Post:

mainData.splice(post, 1) is the problem for delPost! splice changes the varible, while mainData is const!

  • okay so what solution would you suggest? Yes, I tried that for update subscription..but for delete operation, I'm coping the data to variables like `mainData` and `delPost`..that isn't working either. – s develop Jan 23 '18 at 15:11
  • `mainData.splice(post, 1) ` is the problem for `delPost`! `splice` changes the varible, while `mainData` is const! – Mohsen ZareZardeyni Jan 23 '18 at 22:36