zoukankan      html  css  js  c++  java
  • [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.

  • 相关阅读:
    小程序双重for循环实现tab切换小demo
    小程序基础操作小总结
    一道关于类型转换的面试题的研究
    面试准备(6)vue专题
    面试准备(5)一道关于循环,事件执行顺序的题进行剖析
    微信小程序弹出授权用户信息和手机号
    面试准备(4) 作用域 预解析 字面量 arguments 等考察点练习
    ABC135
    CodeForces 1288C
    P4170
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5735188.html
Copyright © 2011-2022 走看看