Encountering a bug: "Undefined property" issue when working with Web Sockets in React Native

I'm a beginner in React Native and Java Script development, and I'm facing an issue while trying to retrieve a JSON object and display it on the client side. I keep getting a "cannot read property of undefined" error when using websockets instead of "Fetch". I've tried debugging the code and confirmed that the JSON is being received from the server. Here's the relevant client-side code:

fetchDataWithSockets() 
    {
        var url='ws://localhost:3000/';
        var ws = new WebSocket( url );
        var object;
        ws.onmessage = (e) => {
          object = JSON.parse(e);

        } 
                this.setState({
                    dataSource: this.state.dataSource.cloneWithRows(object.movies),
                    isLoading: false,
                    empty: false,
                    documents: object.movies
                });

    }

Object on Server:

var object = {
  "title": "The Basics - Networking",
  "description": "Your app fetched this from a remote endpoint!",
  "movies": [
    { "title": "Star Wars", "releaseYear": "1977"},
    { "title": "Back to the Future", "releaseYear": "1985"},
    { "title": "The Matrix", "releaseYear": "1999"},
    { "title": "Inception", "releaseYear": "2010"},
    { "title": "Interstellar", "releaseYear": "2014"}
  ]
}

If anyone could provide some assistance, I would greatly appreciate it :)

Answer №1

When utilizing the <code>object in the this.setState... line, make sure to reposition your this.setState line within the onmessage of the WebSocket. The adjusted code should resemble the following:

fetchDataWithSockets(){
    var url='ws://localhost:3000/';
    var ws = new WebSocket( url );
    var object;
    ws.onmessage = (e) => {
        object = JSON.parse(e);

        this.setState({
            dataSource: this.state.dataSource.cloneWithRows(object.movies),
            isLoading: false,
            empty: false,
            documents: object.movies
        });
    }
}

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

Utilizing DOMPDF in conjunction with jQuery to generate PDF files

Apologies for any language errors in my writing. I am attempting to generate a PDF using a portion of HTML, utilizing jQuery, Ajax, and DomPDF. On the server side, I am using the following code: require_once './dompdf/autoload.inc.php'; if(!em ...

If the user inputs any text, Jquery will respond accordingly; otherwise,

I have a text field that is populated from a database, but if a user decides to change the value, I need to use that new value in a calculation. $('#ecost input.ecost').keyup(function(){ if (!isNaN(this.value) && this.value.length != ...

How can I pass a JavaScript variable through the URL in a Rails 4 application to access it in the controller?

Struggling to pass the value of a JavaScript variable in the URL and then retrieve it in my Rails 4 app controller using param[:my_variable]. Despite trying various methods, none seem to work for me. I am unable to successfully pass my JavaScript variable ...

`Efficiently transform objects from a sizable JSON file into .NET objects in no time`

My current task involves working with a large JSON file containing around 5 million objects and weighing 303MB. The file can be downloaded from here. Here is a snippet of what the JSON file contains: { Reviewer:1, Movie:1535440, Grade:4, Date:'2005- ...

What is the method for retrieving the HTTP request output and saving it to a JSON file?

Currently, I am facing an issue with making a http get request to a url. Although I can retrieve data from the web page successfully, I am struggling to store it in JSON format and extract only the required information. My development environment consists ...

Parsing the CSV file contents according to the specified columns

Currently, I'm involved in a project using AngularJS where I need to extract data from a CSV file column by column using JavaScript. So far, I've successfully retrieved the CSV data and displayed it in the console. While I've managed to sepa ...

Vertical scrollbar in iframe unexpectedly appears immediately after the submit button is pressed

I have designed a contact form that is displayed in an iframe within an overlay div. I have carefully adjusted the dimensions of this div to ensure that there are no scrollbars visible when the form initially appears. However, after filling out the form an ...

Passing events from Swift or Objective-C to JavaScript is a seamless process

A custom class was created with the following condensed version provided. For a reference to the full file, please visit this link. @objc(NativeMethods) class NativeMethods: RCTEventEmitter { @objc(sendEventToJSFromJS) func sendEventToJSFromJS { s ...

Updating the React State is dependent on the presence of a useless state variable in addition to the necessary state variable being set

In my current setup, the state is structured as follows: const [items, setItems] = useState([] as CartItemType[]); const [id, setId] = useState<number | undefined>(); The id variable seems unnecessary in this context and serves no purpose in my appl ...

Activate the click event repeatedly in a loop

I am currently working on a bookmarklet to extract information from my Indiegala bundles that I have purchased. Instead of gifting the entire bundle, I prefer sending individual games one or two at a time as it is more convenient with the individual gift U ...

Struggling to make an AJAX form function properly

I'm running into an issue while setting up a basic AJAX form. My goal is to have a message display on the same page upon successful login using a PHP form through AJAX, but currently, I get redirected to the PHP file after form submission. Can anyone ...

Obtaining the date for the previous month using JavaScript or jQuery

I need to retrieve a specific date in JavaScript. My goal is to obtain the current date based on a variable named frequency, which can have values of Daily, Weekly, or Monthly. if(frequency=="daily") { date='current_date -2 days'; } e ...

Automating Indesign with HTML5 and JavaScript through IDML files

I am currently working on automating IDML files. My goal is to display an IDML template in an HTML5 editor. Within the sample.idml file, I have a basic TextFrame containing the text "Hello World." After unzipping the file and navigating to the stories fol ...

Tips for customizing the cursor to avoid it reverting to the conventional scroll cursor when using the middle click

When you wish to navigate by scrolling with the middle mouse button instead of using the scroll wheel, simply middle-click and your cursor will change allowing for easy scrolling on web pages. Even though I am utilizing style="cursor: pointer" and @click. ...

python: parsing CSV to generate JSON data

Seeking help on creating a nested field from CSV to JSON. The solutions I found on StackOverflow don't quite fit my formatting needs. I have a dataset with one column that needs to be converted into a nested field. Dataset: ID, NAME 1, " ...

JavaScript Class vs Function as Definition

Having trouble locating documentation for this issue. I devised a JavaScript class in the following manner: class Polygon { constructor(height, width) { this.height = height; this.width = width; } area = function() { return this.height ...

Using jQuery to iterate through rendered HTML with the ForEach function

I am utilizing JS/jQuery code to extract the cell value of an ASP DetailsView control (rendered HTML), validate it against a condition, and hide a specific div based on the result. Specifically, the code is examining whether the cell value is formatted lik ...

Adjust the position of an element based on changes in window size using jQuery

Wondering if this question is unique, as I've spent quite some time searching for a solution to this issue without any luck. Perhaps my search criteria aren't correct. I have a navigation bar that becomes fixed when it reaches the top of the vie ...

Include a button alongside the headers of the material table columns

I am looking to customize the material table headers by adding a button next to each column header, while still keeping the default features like sorting and drag-and-drop for column rearrangement. Currently, overriding the headers requires replacing the e ...

Mastering jQuery ajax in Google Chrome Extensions

I have developed a script to fetch data from an external server using JSONP request in jQuery. Please take a look at the code snippet below: $("#submit").click(function() { var state = $("#state").val(); var city = $("#city").val(); $.ajax({ ...