Issue while getting data from firebase realtime database into react redux

Viewed 78

I'm trying to get data from the firebase "realtime database".

words:
0: {somedata},
2: {some data},
3: {some data},
4: {some data},

please note that the key 1 does not exists on firebasse.

here is how the data present in the firebase

The data arrived at the redux reducer correctly like how it preset in firebase "without the key #1", but after dispatching it into the state, I've got a null object for key #1 like the below example.

words: [
   0: {data here}
   1: null
   2: {data here}
   3: {data here}
]

here is how the data present in redux store:

here is the reducer:

here is how the date presents on reducer:

My question is: why the data is not saved in redux store like the below structure:

words: [
   0: {data here}
   2: {data here}
   3: {data here}
   4: {data here}
]
1 Answers

When you store an array in Firebase, it actually stores is as an object with separate number keys (so the 0: { ... }, 1: { ... } in your data).

When retrieve data with sequential, numerical keys from Firebase, it interpret that as an array again.

So when you store/retrieve an entire array, your application code always just sees the array - never the way it is stored as a regular object.


Firebase SDKs and the REST API also interpret sequences as an array when there are a few items missing. It "just" sets those indices to null as shown in your second snippet.

For more on this, see the vintage blog post: Best Practices: Arrays in Firebase.


The best solution when this array coercion gets in your way, is to not use arrays for storing the data. For example, I prefer prefixing those numeric keys with a short string, like "key0", "key2". That way Firebase will never try to convert my data into an array.

Related