0

I'm pretty new in coding. I'm working on ReactJS and I am trying to display in a list all differents categories in my database from Firebase. You can see below the code I wrote:

    import Link from 'next/link'
    import React, { Component } from 'react'
    import firebase from 'firebase'

    export default class extends Page {

        constructor () {
          super()
          this.state = {
            datas: ''
          }
       }

        componentDidMount () {

          firebase.initializeApp(clientCredentials)

      // -------  Connect to the firebase DATABASE -------- ////

      firebase.database().ref().orderByChild("sectionIndex")
          .on("child_added",
            snapshot => {this.setState({datas: snapshot.val().category});},
            error => {console.log("Error: " + error.code);});

        }

        render () {

          return (
            <ul>
              {this.state.datas.map((data, i) => 
              <li key={i}> {data.category} </li>
            </ul>
          )
        }
      }

It says that TypeError: this.state.datas.map is not a function. I believe that the data from firebase is not an array maybe thats why I have this message error...

Here is how my database looks like in Firebase: DB

Maybe the database is not an Array [] but Object {} that's why? If yes, how can I convert it into an Array.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Pierre Trzaska
  • 105
  • 1
  • 3
  • 9
  • 2
    Just console log `this.state.datas` to see what it looks like. Firebase does not have collections so it probably is just a simple Object with numbers as keys. To convert to an Array, look at this question: https://stackoverflow.com/questions/6857468/converting-a-js-object-to-an-array – VanDanic May 30 '17 at 13:45

1 Answers1

6

Firebase returns object from database with snapshot.val().category. If you saved it as array, returned object will look like this:

{
 "1": "data",
 "2": "data2",
}

You can get your array using Object.values(), which gets all values from object and returns array of that values.

I will write saving from database, like this:  

this.setState({datas: Object.values(snapshot.val().category)})

Or rewrite map call to:

Object.values(this.state.datas).map((data, i) => 
          <li key={i}> {data.category} </li>
)
Marin Marković
  • 166
  • 1
  • 5