In last post we have seen how to write data in React and Firebase. In this we are going to go through how to read value and json from firebase realtime Database.
Read simple data from Realtime Database
Now we will open the App.js file of the react app.
First, we have to import firebase as
import * as firebase from 'firebase'
We need to do all the work inside the
componentDidMount() function.firebase.database().ref().child('name').on('value',snap =>{
this.setState({
name:snap.val()
});
});
In the above example, we try to get the value of name from a tree using
.on function. There is a parameter snapshot in .on function. And we will get all results in the snapshot parameter. We are trying to set the value to the state so we can use in our web.Read Json data from Realtime Database
firebase.database().ref().child('userData').on("value", snapshot=> {
var newPost = snapshot.val();
this.setState({
userData:newPost
});
});
In the above example, we try to get the value of userData from a tree using
.on function.Read Array Json data from Realtime Database
firebase.database().ref().child('users').on("value", snapshot=> {
let all = snapshot.val();
let data =[];
for (let i in all){
data.push({
id:i,
Name:all[i].Name,
email:all[i].email,
profile_picture:all[i].profile_picture
});
}
console.log(data);
this.setState({
users:data
});
});
In the above example, we try to get the value of users from a tree using
.on function.Here is the full code of the above examples.
import './App.css';
import * as firebase from 'firebase'
import React, { Component } from 'react'
export default class App extends Component {
constructor(){
super();
this.state={
name:"",
users:[],
userData:{}
};
}
componentDidMount(){
firebase.database().ref().child('name').on('value',snap =>{
this.setState({
name:snap.val()
});
});
firebase.database().ref().child('userData').on("value", snapshot=> {
var newPost = snapshot.val();
this.setState({
userData:newPost
});
});
firebase.database().ref().child('users').on("value", snapshot=> {
let all = snapshot.val();
let data =[];
for (let i in all){
data.push({
id:i,
Name:all[i].Name,
email:all[i].email,
profile_picture:all[i].profile_picture
});
}
console.log(data);
this.setState({
users:data
});
});
}
render() {
return (
<div className="App">
<h1>{this.state.name}</h1>
<div> <h1>User Infromation </h1></div>
<h3>Name:{this.state.userData.Name}</h3>
<h3>Email:{this.state.userData.email}</h3>
<h3>Image:{this.state.userData.profile_picture}</h3>
<div> <h1>All Users</h1>
{this.state.users.map((value)=>{
return(
<div key={value.id}>
<h3>Name:{value.Name}</h3>
<h3>Email:{value.email}</h3>
<h3>Image:{value.profile_picture}</h3>
</div>
)
})}
</div>
</div>
)
}
}
Hope this post will help with you projects. Message if you stuck anywhere.
Enjoy coding...
No comments:
Post a Comment