Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering data in FlatList from firebase

I am using React Native 0.49. I have data fetched from firebase, list of users users/, each item in this list was set like this firebase.database().ref('users/' + userId).set(userInfo) userId is the uid of the currentUser.

Now I am fetching back (in actions - redux):

export function getPeople(){
    return (dispatch) => {
        dispatch(getPeopleRequest());
        getData().then(result => {
            dispatch(getPeopleSuccess(result.val()))
        })
        .catch(error => {
            dispatch(getPeopleFailure(error))
        }); 
    }
}

const getData = () => {
    const userRef = firebase.database().ref('users/').limitToFirst(20);
    return userRef.once('value');     
}

In component, I am trying to render the data in FlatList, but it's not rendering anything, I don't know what I'm doing wrong:

componentDidMount(){
   this.props.getPeople();
}
_renderItem = ({ item }) => (

    <View style={{flex: 1}}>
        <Text>{item}</Text>
    </View>
);

render(){
    const { inProgress, people, error } = this.props.peopleData;
    return (
        <FlatList
            data={people}
            renderItem={this._renderItem} 
        />
    );
}

when console log people this is result: {cpycwkz7exVBzmhaLEtHjMW66wn1: {…}, UbIITfUANmb63cYE2x7dZRZ0pfK2: {…}}

like image 776
Yasir Avatar asked Oct 30 '17 06:10

Yasir


Video Answer


1 Answers

FlatList component expects its data prop to be an array. You are passing it as an Object. You can change it to an array of Objects. Then too in your _renderItem method the item will be an object and it can't be rendered straight away in <Text>, you have to extract a text value from the item object and than render it as: <Text>SOME_TEXT_NOT_AN_OBJECT</Text>

You can convert your people object to an array and pass it to the <FlatList like this:

render(){
    const { inProgress, people, error } = this.props.peopleData;
    let ArrayOfPeopleObject = Object.values(people)
    return (
        <FlatList
            data={ArrayOfPeopleObject}
            renderItem={this._renderItem} 
        />
    );
}

Now each item in the _renderItem method will be an object and you can extract value from any key and render it in the <Text>.

like image 67
Shubhnik Singh Avatar answered Nov 04 '22 20:11

Shubhnik Singh