Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use React Native ListView with MobX?

I am trying to populate a ListView in react native with a MobX's observable array like so:

constructor(props) {
        super(props)
        var dataSource = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
        let dogs = props.store.dogs;
        this.state = { dogs: dogs, dataSource: dataSource };
    }

    render() {

        var dogs = this.state.dogs;
        var dataSource = this.state.dataSource.cloneWithRows(dogs);

        return <ListView
            dataSource={dataSource}
            renderRow={this.renderRow}
            />
    }

But when running the code, renderRow() never gets called. It like the cloneWithRows() method didn't know how to clone the rows.

Have anyone succeeded doing this? (And also getting it to behave that when a dog's name in the list of dogs changes, then the cell in the list will re-render)

Update: more info here https://github.com/mobxjs/mobx/issues/476

like image 786
Yaron Levi Avatar asked Nov 09 '22 10:11

Yaron Levi


1 Answers

If I remember correctly you need to slice the dogs (lol) dogs.slice() as otherwise the ListView won't recognize it as proper array. It might be the case that the component rendered by renderRow needs to be an observer component as well, as it could be invoked asynchronously.

Note that the slicing should be done in the render method and not in the constructor; you want it to happen every time that the collection changes, and not only when the component is constructed.

See also: https://github.com/mobxjs/mobx/issues/476

like image 126
mweststrate Avatar answered Nov 15 '22 13:11

mweststrate