[React Native + Firebase] React Native: Real time database with Firebase -- setup & CRUD

Install:

npm i --save firebase // v3.2.1

 

Config Firebase:

First we need to require Firebase:

import firebase from 'firebase';

Then in 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 you 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", 'answer881215@gmail.com', null);
复制代码

Then one node will be created in the "users" node, 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", "yoona.only@gmail.com", ref.key);
    }

// calling
this.appendOneMoreUser("Yuri", 'yuri.only@gmail.com', null);
复制代码

So under "users" node, we want to append one new node, the uid will 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", "yoona.only@gmail.com", 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.

 

posted @   Zhentiw  阅读(1105)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2014-08-04 [Javascript] Closure Cove, Common mistake
2014-08-04 [Javascript]Clouse Cove, 2 ,Modifying Bound Values After Closure
2014-08-04 [Javascript] Closure Cove, 1
2014-08-04 [Backbone]7. Collection Views, Custom Events
点击右上角即可分享
微信分享提示