How to Update and Delete data to Realtime Database ?
Use update() function for update data to firebase realtime database and use remove() function to delete data to firebase realtime database. Follow the step to update and delete the data for web to realtime database to firebase.
- First setup firebase SDK and Initialize Realtime Database
Updata Data :
update(ref(database, 'PARENT_NODE'), {CHILD_NODE : VALUE}) :import { database } from '<YOUR_FIREBASE_CONFIG_FILE_PATH>';import { update, ref } from 'firebase/database';update(ref(database,'PARENT_NODE'),{CHILD_NODE: VALUE});* First argument : update ref takePARENT_NODE
as reference and update itsCHILD_NODE
withVALUE
.* Second argument : It always takes an object.
For example,
Available data in realtime database :
We want to update mobileNumber soPARENT_NODE
is 'users/userInfo' and as a objectCHILD_NODE
is 'mobileNumber' with its updated value '+1 1111111111'.So code for that is,
import { database } from '<YOUR_FIREBASE_CONFIG_FILE_PATH>';import { update, ref } from 'firebase/database';update(ref(database, 'users/userInfo'), { mobileNumber: '+1 1111111111' });There is second way to write code for the same functionality,TakePARENT_NODE
as 'users' and as a objectCHILD_NODE
is 'userInfo/mobileNumber' with its value '+1 1111111111'.import { database } from '<YOUR_FIREBASE_CONFIG_FILE_PATH>';import { update, ref } from 'firebase/database';update(ref(database, 'users'), { 'userInfo/mobileNumber': '+1 1111111111' });update() return Promise so you can run code on fulfilled and handle errors using '.then()' or 'async/await'. Delete Data :
remove(ref(database, 'REFERENCE_PATH')) :import { database } from '<YOUR_FIREBASE_CONFIG_FILE_PATH>';import { remove, ref } from 'firebase/database';remove(ref(database, 'REFERENCE_PATH'));
'.then( )' : Code for that,
update(ref(database, 'users'), { 'userInfo/mobileNumber': '+1 1111111111' })
.then(() => {
// Run code after successful update
})
.catch((error) => console.log(error));
REFERENCE_PATH
is path location of 'node' whose data will remove.For example,
We want to delete 'mobileNumber' field so for that
REFERENCE_PATH
is 'users/userInfo/mobileNumber'. So code for that is,import { database } from '<YOUR_FIREBASE_CONFIG_FILE_PATH>';
import { remove, ref } from 'firebase/database';
remove(ref(database, 'user/userInfo/mobileNumber'));
'.then( )' : Code for that is,
remove(ref(database, 'user/userInfo/mobileNumber'))
.then(() => {
// Run code after successful deletion
})
.catch((error) => console.log(error));
Related Post
Read data
Setup and Initialize
Write data
Explore
Copyright © 2024, All rights reserved by Firebase Master