2

I have 2 files Server.js and Servicedesk.js, I work with socket.io and ReactJS. I want to compare an array from Server.js (my socket.io file) with an array from Servicedesk.js. In Servicedesk.js I have the following code:

class Servicedesk extends React.Component {
    constructor(props) {
        super(props);    

    this.state = {
       messages: [],
    };

    socket.on('updateRooms', function(combMessages) {
            console.log(combMessages.length);
            console.log(this.state.messages.length);

            let intersection = combMessages.filter(x => this.state.messages.includes(x));
            console.log(intersection);
    });
  }
}

And in Server.js:

let combMessages = [];

I'm passing the combMessages to the Servicedesk.js but how can I compare both? Because I can't do something like:

let intersection = combMessages.filter(x => this.state.messages.includes(x));

Because I'm getting this error:

TypeError: undefined is not an object (evaluating 'this.state.messages')

3
  • Can you show the complete code of Servicedesk.js? The lambda function passed as parameter to combMessages.filter() cannot "find" the this.state.messages, and that's tem reason to the error given Commented May 14, 2018 at 13:46
  • @MatheusReis I've updated the code Commented May 14, 2018 at 13:53
  • it's probably that you don't have this.state.messages when you call it in 'console.log(this.state.messages.length);' use the inspector of your web browser to verify this. if that's what happen, then you just need to add a condition if(this.state.messages != undefined) Commented May 14, 2018 at 13:57

1 Answer 1

1

In the socket.on(), your

 function(combMessages) { 
     console.log(combMessages.length); 
     console.log(this.state.messages.length); 
     let intersection = combMessages.filter(x => this.state.messages.includes(x)); 
     console.log(intersection); 

}

Can't see the context of your component. So, you should use arrow function(See the docs), that will bind the context to your function,like this:

 socket.on('updateRooms',(combMessages) => {
     console.log(combMessages.length); 
     console.log(this.state.messages.length); 
     let intersection = combMessages.filter(x => this.state.messages.includes(x)); 
     console.log(intersection); 
 })
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.