Yaron Levi
Yaron Levi

Reputation: 13079

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

Upvotes: 5

Views: 1398

Answers (1)

mweststrate
mweststrate

Reputation: 4978

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

Upvotes: 1

Related Questions