Install:
// v3.2.1
Config Firebase:
First we need to require Firebase:
from ' Firebase ';
Then on the component constructor, we need to init Firebase:
constructor(props){
super(props); // Initialize Firebase var config = {
apiKey: "<api_key>",
authDomain: "<authDomain>",
databaseURL: "<databaseURL>",
storageBucket: "<storageBucket>",
};
firebase.initializeApp(config);
}
The config can easily get from the your Firebase App page.
Create New Node:set ()
writeUserData(userId, name, email, imageUrl) {
firebase.database().ref(‘users/‘ + userId).set({
username: name,
email: email,
profile_picture : imageUrl
});
} // calling this.writeUserData(1, "Zhentian Wan", ‘[email protected]‘, null);
Then one node would be created in the "Users" node, and the UID is "1".
Create new Child Node:push ()
appendOneMoreUser(name, email, imageUrl){
let ref = firebase.database().ref().child(‘users‘).push({
username: name,
email: email
}); this.updateMe("Yoona", "[email protected]", ref.key);
} // calling this.appendOneMoreUser("Yuri", ‘[email protected]‘, null);
So under "Users" node, we want to append one new node, the UID would be generated randomly.
The "ref" object contains "key" prop which ref to the UID in the database.
Update one node:update ()
updateMe(name, email, key){ const update = {
username: name,
email
};
let ref = firebase.database().ref(‘users/‘ + key).update(update)
.then((res)=>{
console.log("Data has been updated ");
});
} // calling: const ref = firsebase.database().ref().child(‘users‘).push(user); this.updateMe("Yoona", "[email protected]", ref.key);
Update () and set () methods both return Promise. So you can chaining. then () onto it.
Delete Node:remove ()
deleteMe(){
firebase.database().ref(‘users/1‘).remove();
}
Delete the UID = 1 user.
[React Native + Firebase] React native:real Time Database with Firebase-Setup & CRUD