React Native - ListView with Firebase

suggest change

This is what I do when I’m working with Firebase and I want to use ListView.

Use a parent component to retrieve the data from Firebase (Posts.js):

import firebase from 'firebase';
import PostsList from './PostsList';

class Posts extends Component{
    constructor(props) {
        super(props);
        this.state = {
            posts: []
        }
    }
    
    componentWillMount() {
        firebase.database().ref('Posts/').on('value', (data) => {
            this.setState({ posts: data.val() });
        });
    }

    render() {
        return <PostsList posts={this.state.posts}/>
    }
}
class PostsList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            dataSource: new ListView.DataSource({
                rowHasChanged: (row1, row2) => row1 !== row2
            }),
        }
    }

    getDataSource(posts) {
        if (!posts) {
            return this.state.dataSource.cloneWithRows([]);
        }
        return this.state.dataSource.cloneWithRows(posts);
    }

    componentDidMount() {
        this.setState({dataSource: this.getDataSource(this.props.posts)});
    }

    componentWillReceiveProps(props) {
        this.setState({dataSource: this.getDataSource(props.posts)});
    }

    renderRow = (post) => {
        return (
            <View>
                <Text>{post.title}</Text>
                <Text>{post.content}</Text>
            </View>
        );
    }

    render() {
        return(
            <ListView
                dataSource={this.state.dataSource}
                renderRow={this.renderRow}
                enableEmptySections={true}
            />
        );
    }
}

Import firebase in each file that calls it. Initialize the app once, usually in the root component. Later imports share that default app. ListView and Component also need to be imported in PostsList.js. data.val() is often a map of posts, which cloneWithRows accepts. Remove the listener in componentWillUnmount so it does not call setState after the screen is gone.

This is the solution someone suggested in a question I asked when I was struggling with ListView. I thought it would be nice to share it.

Source: http://stackoverflow.com/questions/38414289/react-native-listview-not-rendering-data-from-firebase

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents