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

來源:互聯網
上載者:User

標籤:

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", ‘[email protected]‘, 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", "[email protected]", ref.key);    }// callingthis.appendOneMoreUser("Yuri", ‘[email protected]‘, 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", "[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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.