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.

1
  • 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: stackoverflow.com/questions/6857468/… Commented May 30, 2017 at 13:45

1 Answer 1

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>
)
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.