How to retrieve data from firebase in React? [on hold]

问题: I am making a todo-list app using React. I'm able to save data into firebase database. However, I don't know how to retrieve those data and put them in JSX. I can print the...

问题:

I am making a todo-list app using React. I'm able to save data into firebase database. However, I don't know how to retrieve those data and put them in JSX. I can print them in the console. Currently, I only output the todo lists by typing in the bar and press enter.

Here is my code. It's kinda messy.

   import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import firebase from 'firebase';

var config = {
    apiKey: "**********************",
    authDomain: "react-to-do-list-a8f6d.firebaseapp.com",
    databaseURL: "https://react-to-do-list-a8f6d.firebaseio.com",
    projectId: "react-to-do-list-a8f6d",
    storageBucket: "react-to-do-list-a8f6d.appspot.com",
    messagingSenderId: "673689778313"
};
firebase.initializeApp(config);

const database = firebase.database();
const ref = database.ref('todos');




// const todos = []
class Index extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            todo: '',
            todos: [],
            // database: 
        }
        this.handleInput = this.handleInput.bind(this)
        this.addTask = this.addTask.bind(this)
        this.check = this.check.bind(this)
    }
    handleInput(e) {
        this.setState({
            todo: e.target.value
        })
    }
    addTask(e) {
        if (e.keyCode === 13) {
            this.setState({
                todos: this.state.todos.concat(this.state.todo)
            })
            e.target.value = ''
            ref.push(this.state.todo)
        }
    }
    check(e) {
        if (e.target.style.textDecoration === "") {
            e.target.style.textDecoration = " line-through"
        } else {
            e.target.style.textDecoration = ""
        }
    }


    render() {

        ref.on('value', gotData, errData)

        function gotData(data) {
            let todos = data.val()
            // console.log(todos)
            let keys = Object.keys(todos)
            // console.log(keys)
            for (let i = 0; i < keys.length; i++) {
                let key = keys[i]
                let todo = todos[key]
                console.log(todo)
            }
        }

        function errData(err) {
            console.log('Error !')
            console.log(err)
        }

        return (
            <div className='container'>
                <h1>To Do List</h1>
                <input value={this.state.term} onKeyDown={this.addTask} onChange={this.handleInput} placeholder="  Add your tasks here"></input>
                <ul>
                    {this.state.todos.map(x => {
                        return (
                            <li>
                                <input type="checkbox" id={x} name={x} value={x} />
                                <label for={x}>{x}</label>
                            </li>
                        )
                    })}
                </ul>
            </div>
        )
    }
}
ReactDOM.render(<Index />, document.getElementById('root'));

回答1:

As firebase database is a real time DB, which means it gives you a reference to where data is and can trigger you whenever the data at the reference changes, this allows you to capture snapshots of data at the given reference.

You are almost correct to use firebase.database().ref().on('value') method to get the data at the reference.

You can further add a callback like the this:

firebase
      .database()
      .ref(
        firebase_basepath + `${tenantId}/${userId}/task/product/${referenceId}`
      )
      .on("value", snapshot => {
        console.log("FireB ",snapshot)
        if (snapshot && snapshot.exists()) {
           //Set values in state which can be extracted in jsx in render. 
        }})

Now with the state change the function will re render and the values can be set in the jsx.

  • 发表于 2019-03-16 09:58
  • 阅读 ( 208 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除