Reputation: 79
I'm programming an app to understand how websocket functions in react native. I already get the data from the websocket in JSON format and I can print them out in my console with console.log, but I would like to put just a part of the JSON Object on a button, for example if my JSON Object looks like this :
var myJSON = '{"Question": "Want to join?", "Answer":"yes" }';
So I would like to write the String "Want to join?" on a Button. I tried it like this in the following code but I get the error : undefined is not an object (evaluating 'this.state.text = JSON.stringify(myObj.Question)')
Here is my code ( without my stylesheets):
import React, { Component } from 'react';
import {AppRegistry,StyleSheet,Text,View,Alert,AsyncStorage,TouchableOpacity} from 'react-native';
export default class ExampleW extends Component {
constructor(props) {
super(props);
this.state = {
text: '',
}
}
async onButtonPressed(){
Alert.alert('The button was pressed!')
}
getText(){
return (this.state.text);
}
componentDidMount(){
var ws = new WebSocket('ws://URL');
ws.addEventListener('message', function (event) {
console.log('Message from server', event.data);
var myObj = JSON.parse(event.data);
console.log('Typ: ',myObj.Type);
console.log('Question:', myObj.Question);
this.state.text = JSON.stringify(myObj.Question);
});
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<View style ={styles.buttonContainer}>
<TouchableOpacity style = {styles.buttonAccount}
onPress = {this.onButtonPressed.bind(this)}>
<Text style = {styles.buttonText}> {this.getText()} </Text>
</TouchableOpacity>
</View>
</View>
);
}}
I don't understand how to convert correctly the JSON object and how to save it in this.state.text and why I cannot display it on my button. Thanks for any help!
Upvotes: 0
Views: 3858
Reputation: 2458
You correctly parse the JSON object. The resulting myObj
is a JavaScript object, so you can directly access its values using e.g. myObj.Question
. To set the component's state, use setState
inside componentDidMount
:
ws.addEventListener('message', function (event) {
console.log('Message from server', event.data);
var myObj = JSON.parse(event.data);
this.setState({text: myObj.Question});
}
I haven't personally built anything with websockets in RN but as a general principle any listeners set up in componentDidMount
should be removed in componentWillUnmount
.
Upvotes: 1