0

Running some example code, I am running into an issue where the listView does not properly rerender a list that has been modified. For example, I have a hardcoded array of objects like:

datasetsItems = [
    {firstObjectWithMultipleParams},
    {secondObjectWithMultipleParams},
    ...
]

Then I created a button that did the following:

datasetsItems.splice(1,1) // To delete the object at index 1
this.setState({dataSource: this.state.dataSource.cloneWithRows(
    datasetsItems
)});

However, this renders it with the last object in the array deleted, not the one specified at the index. I checked in the debugger and the splice function is working properly and deleting the requested object so it is not an issue with the splicing function.

I then tried the following:

datasetsItems = [...datasetsItems.slice(0,1),...datasetsItems.slice(2,datasetsItems.length)];
this.setState({dataSource: this.state.dataSource.cloneWithRows(
    datasetsItems
)});

And this works and renders the list as expected without the object at index 1. So then I did the following, just to test:

datasetsItems.splice(1,1);
let newDs = datasetsItems.slice();
this.setState({dataSource: this.state.dataSource.cloneWithRows(
    newDs
)});

But this doesn't work, and fails in the same way as the first example.

Is there a reason for this behaviour? I am also wondering if the way I am doing it with slicing gets rid of React's ability to just modify the changed row and therefore fully rerenders everything?

2 Answers 2

2

You should use a clone of your original dataset to update the state. I had the same problem and managed to fix it by deep copying the array before doing this:

this.setState({
   dataSource: this.state.dataSource.cloneWithRows(newDs)
});

Here is a piece of my code:

//delete some items from old_array

var new_array = JSON.parse(JSON.stringify(old_array));

this.setState({
   dataSource: this.state.dataSource.cloneWithRows(new_array)
});

It might not be the best solution.

0

When an empty data is involved like fetch did not find a data result, I used like this to flush the ListView :

this.setState({ dataSource: 
                    this.state.dataSource.cloneWithRows({}),
                loaded: true,
                    });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.