0

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!

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

this.setState gives me the error : this.setState is not a function
Might be because of this being wrong. Try setting let self = this; inside componentDidMount before initiating the event listener and use self.setState({text: myObj.Question});. Does that work?
do you think it would be better to store myObj.Question into Asyncstorage or localstorage instead of this.state.text?
If Question is expected to rarely or never change, or needs to be available offline, it probably is wiser to store than to query each time. On the other hand this query is very light, so from a performance perspective it probably doesn't matter much.

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.