Reputation: 674
I am trying to display the elements in LISTVIEW in react native
In this section I am trying to populate the data and check for the row similarity and set the dataSource.
constructor(props) {
super(props);
this.socket = SocketIOClient('http://localHost:3000');
this.socket.on('Channel1', this.onReceivedMessage);
var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = {
ds: ['rCode'],
dataSource: ds
};
}
Here the rCode is being displayed properly in the listView
componentDidMount() {
this.setState({
dataSource:this.state.dataSource.cloneWithRows(this.state.ds),
})
}
Here, i am not able to display newDs in the listView it gives me error
onReceivedMessage(messages) {
rcodeSet.add(JSON.stringify(messages.rCode));
var newDs = [];
newDs = Array.from(rcodeSet);
this.setState({
dataSource:this.state.ds.cloneWithRows([...newDs]),
})
}
error:
undefined is not an object (evaluating 'this.state.ds')
Upvotes: 0
Views: 54
Reputation: 30360
This is because the context of your onReceivedMessage
callback is not that of your component instance.
As a result, this.state
is undefined, because onReceivedMessage
is executed in the global/window context (ie where this.state
is not defined), rather than in context of your component instance.
To call onReceivedMessage
from the context your component instance, try adjusting the code in your component constructor to this:
constructor(props) {
super(props);
this.socket = SocketIOClient('http://localHost:3000');
// Wrap the callback with a lambda function, so
// that onReceivedMessage is called from the context of your component
this.socket.on('Channel1', (messages) => this.onReceivedMessage(messages));
var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = {
ds: ['rCode'],
dataSource: ds
};
}
To better understand the details of function context, and arrow functions, see this MDN article
Upvotes: 1