I am having some difficulty obtaining data from multiple Firebase .on
calls. The problem is that I am getting repeat listings because I am pushing the data into an array called items
, but I am not sure how I can clear this array when the data should be updated (causing repeats). I have tried using componentWillUpdate()
and componentDidUpdate()
lifecycle methods, but the .on
calls seem to update without alerting them.
I would place the items array inside one of the .on
calls, but then I am not sure how I can push data into it from the other '.on' calls.
The way my database is structured is that there are objects called "cars", each "cars" object can have multiple properties, the most important (for me) being "model". There are several cars that have the same model, but I am trying to get the very last "cars" object for each model. So, if I have Accord, Civic, Sentra, etc, I want the last Accord, the last Civic, the last Sentra, and so on.
This is the code I am currently using:
import React from 'react';
import { View, Text, FlatList } from 'react-native';
import firebase from 'react-native-firebase';
import TypeItem from './TypeItem';
DB = firebase.database().ref('cars/');
export default class LatestType extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
data: []
};
this.pushReports = this.pushReports.bind(this);
this.makeRemoteRequest = this.makeRemoteRequest.bind(this);
}
makeRemoteRequest = () => {
let items = [];
models.forEach(element => { //models is an array of the list of models
this.pushReports(element, items);
});
console.log("These are the items from Status Screen: ",items);
}
pushReports = (model, items) => {
let item = {};
DB.orderByChild("model")
.equalTo(model)
.limitToLast(1)
.on("child_added", snap => {
item = {
key: snap.key,
type: snap.val().type,
model: snap.val().model,
}
items.push(item);
this.setState({
data:items
});
});
}
componentWillMount(){
this.makeRemoteRequest();
}
componentWillUnmount(){
DB.off();
}
render() {
return (
<View>
<FlatList
data={this.state.data}
renderItem={({item}) => <TypeItem item={item} />}
/>
</View>
);
}
}