Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

485
Visualizações
How can I fetch Firebase data (Realtime Database) that is an object, not an array?

I'm new to coding and learning React Native and Firebase.

I'm trying to fetch data from Firebase Realtime Database using Firebase API.

class UpdatedItem extends React.Component {
  state = {
    loading: false,
    data: [],
    page: 1,
    error: null,
    fullData: []
  }

  componentDidMount() {
    this.makeRemoteRequest()
  }

  makeRemoteRequest = () => {
    const { page } = this.state
    const url = `https://example-default-rtdb.firebaseio.com/dinosaur.json`
    this.setState({ loading: true })

    fetch(url)
      .then(res => res.json())
      .then(res => {
        this.setState({
          data: page === 1 ? [...this.state.data, ...res] : [...this.state.data, ...res],
          error: res.error || null,
          loading: false,
          fullData: res
        })
      })
      .catch(error => {
        this.setState({ error, loading: false })
      })
  }

  render() {
    console.log([...this.state.data])

I succeeded fetching data of an array as below.

[ {
  "height" : 2.1,
  "length" : 12.5,
  "name" : "lambeosaurus",
  "weight" : 5000
}, {
  "height" : 4,
  "length" : 9,
  "name" : "stegosaurus",
  "weight" : 2500
} ]

(Data in an array)

Array [
  Object {
    "height": 2.1,
    "length": 12.5,
    "name": "lambeosaurus",
    "weight": 5000,
  },
  Object {
    "height": 4,
    "length": 9,
    "name": "stegosaurus",
    "weight": 2500,
  },
]

(Result in the console)

But failed to fetch data of an object.

{
  "lambeosaurus" : {
    "height" : 2.1,
    "length" : 12.5,
    "weight" : 5000
  },
  "stegosaurus" : {
    "height" : 4,
    "length" : 9,
    "weight" : 2500
  }
}

(Data in an object)

Array []

(Result in the console)

Can I know what I'm missing and how to fetch data of an object, not an array? Thank you for your help in advance.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The difference here is that the second one comes in as an object but you're still using array destructuring in your setState:

this.setState({
  data: page === 1 ? [...this.state.data, ...res] : [...this.state.data, ...res],
  ...
})

^ this pattern ([...array, ...array]) works for arrays which is why you get the data in the first one. But when the data is an object, you need a different pattern:

this.setState({
  data: page === 1 ? {...this.state.data, ...res} : {...this.state.data, ...res},
  ...
})

^ notice the curly brackets - this is how you destructure an object into a new object.

Now when you console.log([...this.state.data]), your don't need to destructure it again. If you just console.log(this.state.data), you'll see that you have an array for the first one and an object for the second.

Finally, because you shared this bit of code, you should also know something about your setState in general - if you want to update state like this, using the previous value as part of your update, you'll want to access the previous state from setState like so (I'll use the object code here but works for arrays or anything else as well):

this.setState((previousState) => ({
  data: page === 1 ? {...previousState.data, ...res} : {...previousState.data, ...res},
  error: res.error || null,
  loading: false,
  fullData: res
}))
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda