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