I'm currently working on an app to explore the functionality of websockets in react native. I have successfully retrieved data from the websocket in JSON format and can output it to the console using console.log. However, my goal is to display a specific part of the JSON object on a button. For instance, if the JSON Object looks like this:
var myJSON = '{"Question": "Want to join?", "Answer":"yes" }';
I want to display the string "Want to join?" on a Button. My attempt in the code snippet below resulted in an error: undefined is not an object (evaluating 'this.state.text = JSON.stringify(myObj.Question)')
Below is the code snippet excluding 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('Type: ',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'm struggling with converting the JSON object correctly and saving it in this.state.text. Additionally, I'm having trouble displaying it on my button. Any help or guidance would be greatly appreciated. Thank you!