Using React Native to integrate a JSON string into a button

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!

Answer №1

You've successfully parsed the JSON object and now have a JavaScript object named myObj. This allows you to access its values directly, such as myObj.Question. To update the component's state, make use of setState within the componentDidMount method:

ws.addEventListener('message', function (event) {
    console.log('Received message from server:', event.data);
    var myObj = JSON.parse(event.data);
    this.setState({text: myObj.Question});
}

While I haven't personally worked with websockets in React Native, it is good practice to remove any listeners set up in componentDidMount within the componentWillUnmount method.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am facing an issue with Angular 14 and Webpack 5, where certain unnecessary nodejs modules seem to be hindering me from successfully serving

I have recently started working on a cutting-edge Angular 14 application. My current node version is v14.20.0, and npm version is 8.17.0. Despite my best efforts, I seem to be facing an issue with multiple nodejs dependencies being included in my project ...

AngularJS Partial Views: Enhancing Your Website's User Experience

As a newcomer to the world of Angular, I am seeking guidance on a specific issue. I have encountered a one-to-many relationship scenario where one Category can have multiple Product items. The challenge lies in my layout page setup where I display various ...

Using Javascript to test a specific item in an asp Listbox

Let's consider a scenario where there is ListBox1 containing the following listitem: <asp:ListItem Value="No.1">No.1</asp:listitem> In addition, we have a label for a test purpose: <asp:Label ID="lblLabel" runat="server" Text="Label ...

Exploring Node.js with a straightforward illustration and tackling the EPERM error

const server = require('http').createServer(function(req, res){ }); server.listen(8080); This code snippet is causing an error to be displayed in the console: $ node node_server.js node.js:201 throw e; // process.nextTick error, or &apos ...

Show the current Date and Time dynamically using only one line of JavaScript code

After running this command, I encountered an issue: $("#dateTime").text(new Date().toLocaleString()); The result displayed was 2/21/2020, 10:29:14 AM To make the time increase every second, I attempted this code: setInterval($("#dateTime").text(new Dat ...

In order to ensure that the multiselect bootstrap dropdown options drop outside of the div and prevent scroll bubbling, there are specific

I am trying to customize a bootstrap multiselect dropdown located within a div. You can find an example of what I'm working on at this link: http://jsfiddle.net/The_Outsider/8watL2L1/9/ In my design, I want the multiselect dropdown options to drop ou ...

Connecting NGINX to a Node.js cluster with proxy_pass

After setting up both a NGINX server and a node.js process, the node.js code structure is as follows: function initiateCluster() { var numCPUs = require('os').cpus().length; if (cluster.isMaster) { // Fork workers. for (var i = 0; i ...

The submission form is being triggered immediately upon the page loading

I have a form on the landing page that sends parameters to Vuex actions. It functions correctly when I click the submit button and redirects me to the next page as expected. However, there seems to be a problem. Whenever I open or refresh the page, the par ...

Using jQuery to extract a href URL from a div tag with jQuery

Is it possible to extract the href urls from anchor tags within a div tag? <div id="testing"> <a onclick="http://google.com">google</a> <a href="http://facebook.com">facebook</a> <a onclick="http://gmail.com">gmail< ...

Create a new cookie in Angular if it is not already present

I am looking to check if a cookie is set in Angular. If the cookie is not found, I want to create a new one. Currently, I have this code snippet: if ($cookies.get('storedLCookie').length !== 0) { $cookies.put('storedLCookie',' ...

Is it allowed to use an ID as a variable identifier?

One method I often use is assigning a variable with the same name as the id of an element, like this: randomDiv = document.getElementById("randomDiv"); randomDiv.onclick = function(){ /* Do something here; */ } randomDiv.property = "value"; This tech ...

Angular 6: Dealing with Type Errors in the HttpClient Request

I am encountering issues with my services. I am attempting to retrieve a list of media files (generated by NodeJS, which generates a JSON file containing all media items). Although I can successfully fetch the data, I am facing an error stating "Property & ...

Having trouble determining the total amount in my online shopping cart

I am facing an issue with the shopping cart I created, which consists of two components (Productlist and Cart List). When I click on the 'add to cart' button in the Product List, it successfully moves into the service file and then to the Cart Li ...

Using a JSON database to implement various user levels in a domain model

Here is the domain model that I believe to be accurate. I am currently attempting to implement this on a JSON database, but I am uncertain if I am headed in the right direction. From my understanding of JSON, there are no inherent relationships between obj ...

Trigger a pop-up alert box when the jQuery event $(document).ready is fired within a Smarty template

I'm currently attempting to make a popup message display when the document is fully loaded. Although I have successfully integrated Google Maps on another page, this task seems to be more challenging. Below is the code snippet: <html> < ...

Utilize range slider to refine dataset

I have implemented a jquery datatable along with the range.slider plugin. My goal is to apply the range slider to filter out data in the last column. In my attempt, I am using search.push to accomplish this filtering process. Below is an example of my i ...

a hyperlink not functioning properly after the # symbol

I’ve been attempting to obtain the URL in order to share it on Google Plus. I’ve experimented with different codes, but the issue is that the ID value is concealed within the URL, making it impossible to directly pass the link in the "a href" tag. The ...

Serializing a JSON object to a C# class

Currently, I am tackling the task of deserializing a Json Object into a class in .NET Visual Studio 2015 on Windows 7. public class1 { [JsonProperty(TypeNameHandling = TypeNameHandling.Objects)] public Class1 data1; public Class2 data2; } pub ...

Activate a monitoring pixel with a click of your mouse

I have a tracking pixel that is typically placed in the body of a "installation success" page: <img src="http://domain.com/adclick.php" width="1" height="1" border="0" /> However, I want to trigger this pixel when someone clicks on a download butto ...

Struggling with configuring the DEFAULT_VIEW_INCLUSION setting for Jackson views

If you're looking for more information on Jackson views, check out the official documentation available at . According to the docs, you should use the following line of code to exclude properties that are not explicitly mapped to a view: objectMapp ...