0

I am trying to fetch a list of Restaurants from the firebase realtime database,
my code snipped for that fetching the data -

_isMounted = false;

state :{
  data: [],
}

constructor(props){
  super(props)

  this.state = {
    data:[],
  }
}

componentDidMount(){
  this._isMounted = true
  this.getData()
}

componentWillUnmount(){
  this._isMounted = false
}

getData(){
  firebase.database().ref('Restaurants/').on("value", snapshot =>{
    let restaurantList = snapshot.val();
    console.log(restaurantList)
    this.setState({data: restaurantList})
  });
}

The data structure on Firebase is as follows -
Firebase data


The console output for the array restaurantList is -

Array [
  undefined,
  Object {
    "location": "Testing data",
    "name": "Time Traveller",
    "rating": 4.5,
    "tags": "Indian, Asian",
  },
  Object {
    "locations": "Testing data",
    "name": "Novelty",
    "rating": 4.5,
    "tags": "Indian",
  },
]

I am not sure from where I am getting the undefined item in the array.

1 Answer 1

3

Try the following:

getData(){
  firebase.database().ref('Restaurants/').on("value", snapshot =>{
  snapshot.forEach((childSub) => {
    let key = childSub.key;
    let restaurantList = childSub.val();
    console.log(restaurantList);
   });
  });
}

The undefined is the key, try iterating inside the keys and retrieving the data

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.