The React Native ListView fails to refresh after sorting or when new data is retrieved

Working on a react native application with a sortable ListView, where data is fetched from JSON and updated periodically. However, facing issues as the list does not update in either scenario.

Even after verifying that the array matches expectations before cloning it into the ListView.DataSource, there seems to be no update in the DataSource.

Despite attempting deep cloning of the array, the problem persists.

Below is a snippet showcasing the code:

Initialization of ListViewDataSource:

constructor(props) {
        super(props);
        var ds = new ListView.DataSource({
            rowHasChanged: (r1, r2) => (r1.value !== r2.value)
        });
        this.state = {
            dataSource: ds,
            sorting: 'availableCapacity',
            sortingOptions: ['name', 'availableCapacity']
        }
    }

Refreshing/Sorting the array and updating DataSource: (Triggered by a button press or new data arrival)

refreshList(sortBy) {
    if (sortBy === undefined)
        sortBy = this.state.sortBy;
    var array = this.props.dataToSortAndDisplay;
    if (sortBy == 'option1')
        array.sort(this.sortByVar1);
    else if (sortBy == 'option2') {
        array.sort(this.sortByVar2);
    }
    this.setState({
        dataSource: this.state.dataSource.cloneWithRows(array)
    })
}

Tried deep cloning the array using a recursive function but with no success:

cloneData(data) {
    if (data instanceof Array || data instanceof Object) {
        var newData = [];
        for (var k in data) {
            newData[k] = this.cloneData(data[k]);
        }
        return newData;
    }
    else {
        return data;
    }
}

Also attempted cloned using

JSON.parse(JSON.stringify(array))
since the data originates as parsed JSON. Yet, the issue remains unresolved.

If anyone can assist in identifying what might be incorrect here, it would be greatly appreciated. Struggling with a seemingly simple task of updating a ListView.

Thanks in advance.

Answer №1

To enhance the efficiency of your code, consider initializing the ds variable outside of the constructor:

var ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => (r1.value !== r2.value) });
class SampleApp extends React.Component{

  constructor(props) {
    super(props)
    this.state = {
        dataSource: ds
    }
  }

  componentDidMount() {
    this.setState({ dataSource: ds.cloneWithRows(data) })
  }

  render() {
    return (
      <View style={ styles.container }>
        <ListView
        dataSource={ this.state.dataSource }
        renderRow={ (rowData) => <Text>{ rowData }</Text> }
        />
      </View>
    );
  }
}

For a simple example, you can check out a demo here.

Answer №2

After much embarrassment, I finally solved my issue. It turns out the ListView wasn't to blame at all. The real problem was that my cells were saving data in the state when they mounted, but failing to update it when receiving new props.

Once I made the switch to using props directly instead of relying on state, everything fell into place and started functioning as expected.

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

Error in Node-Fetch Mapping: Unable to access property 'map' of an undefined entity

Encountering an issue with the "map" section when attempting to run it - receiving an error message stating "Cannot read property 'map' of undefined" The customers constant is defined above, so I'm unsure where the undefined value is origin ...

Tips for Disabling Alert Pop-ups when Launching Desktop Applications from a Browser

Is there a way to prevent the alert pop-up when launching a desktop application from a web browser? For instance, when typing calculator:// in the browser, we want to eliminate the alert box using an Angular TypeScript file. see image reference ...

Encountering a puzzling issue with React JS and Redux, where using fetch consistently

I want to make an API request without using ajax call, as importing the whole library for just that seems unnecessary. Instead, I decided to follow the fetch function approach outlined in the Redux documentation (which I recently migrated with). import f ...

When attempting to display the image file path using the JavaScript API Notification in Angular, there is a challenge in

Hello fellow developers, I am currently facing an issue with retrieving a local image from my assets folder and displaying it on a new Notification object generated by the Web Notification API. I have an image in my assets folder with a .jpeg extension. ...

Toggling the form's value to true upon displaying the popup

I have developed an HTML page that handles the creation of new users on my website. Once a user is successfully created, I want to display a pop-up message confirming their creation. Although everything works fine, I had to add the attribute "onsubmit= re ...

Executing `removeChild` within a timeout during page load does not yield the expected results

I have an HTML div that is designed to contain dynamically generated children. These children are meant to be removed from the list after a specific amount of time (e.g. 1000 ms). Although some people have experienced scope issues with timeout functions, ...

Can a Jquery *compiler* be developed?

Upon encountering this informative question, the idea of creating a jQuery compiler crossed my mind. The concept was to design a tool that could translate jQuery code into raw JavaScript code for execution. In my imagination, the process of executing a bl ...

Tips for arranging information in ng-repeat using nested objects within JSON data on AngularJS

Looking to display an array of object properties in an Angular view. Here is the object: $scope._Json = { "foo": { "ItemDimension1": { "Item": "item1", "ItemIndex": 1, "SelectedItems": [{ "C ...

setTimeout is only effective for durations less than 1000 milliseconds

I am trying to implement a timeout function that displays an alert two seconds after a form is submitted. The code I have tried using does not seem to be working as expected: $(document).ready(function() { $("#newsletter").submit(function() { setTi ...

Tips to Avoid Multiple Executions of Javascript Code due to Caching

When I make a request to my Asp.net-MVC application, it returns a partial-view. public ActionResult AccountDetails() { return PartialView("~/Views/partials/Account/Details.cshtml"); } To load the partial view in my form, I use the following ...

What is the method to configure the current host for the callbackURL in Passport strategy?

Currently, I am implementing the Passport-Linkedin strategy within Express to enable users to log in using their LinkedIn profiles. The code snippet I am working with is as follows: passport.use(new LinkedInStrategy({ consumerKey: config.linkedin.LIN ...

The Axios request for the concatenated URL is failing to execute

Encountering an issue with Axios in node js. Here's the code snippet: let callResult = await axios.get(urlData, config) The configuration object used is as follows: let config = { headers: { 'X-Token': token } ...

When utilizing NavLink in React Router Dom for routing to an external link, a local host is automatically included in the prefix

I'm currently experiencing an issue with routing to an external link using React Router Dom 6.4. It seems that the localhost path is being appended to the URL. Can anyone provide insight on why this might be happening? localhost:3000/#/http://www.sav ...

Issue in NextJS: During project build, component props become undefined even though they function properly in development mode

Despite functioning properly in dev mode, a component is throwing an error during the build process. It claims that the 'open' prop is undefined, even though it behaves correctly and outputs the right result when console logged on localhost. cons ...

Is it possible to display a thumbnail image in a separate full-sized window by using CSS or JavaScript?

I am currently utilizing a program called WebWorks 2020.1 that automatically creates <img> tags from my FrameMaker source input when published to DHTML. Unfortunately, I do not have the ability to directly modify the HTML <img> or <a> tag ...

How can I dynamically update the content of the right side of the side navbar by clicking on navbar links?

I have a side-navigation bar with content on the right side. How can I display specific content on the right side when clicking on a navigation link? For example, only show the name when clicking on the name link and only show the password field when click ...

Is there a method to modify the arrangement in which 3 specific HTML elements are displayed (i.e., their hierarchy in relation to one another)?

I have 3 "p" elements and I'm trying to find a way to change the order in which they load on the page using JS or CSS. Below is an example of what I've attempted so far. When you click on the first box labeled "about 1," it opens up and displays ...

Discovering the process of obtaining information from a restful API using javascript

I am working on a desktop application using C# (Windows Forms) that includes a web browser component and utilizes JavaScript. My goal is to create a weather forecast for Bulgaria. However, I am unsure about how to retrieve data from the API server. I curr ...

Troubleshooting a malfunctioning ember.js HTML output

I'm currently facing a challenging debugging task to figure out why this specific code snippet is failing: Here is the template causing issues: <p class='navbar-text pull-right header-user-info'> {{#if currentUser.isSignedIn}} {{#i ...

Adjust the position of elements to prevent overlap

I'm facing a problem with elements overlapping on my website. The navbar is sticky, meaning it slides down the page when scrolling. Additionally, I have a "to-top" button that automatically takes you to the header when clicked. I want the "to-top" but ...