Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve data from firebase in React? [closed]

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'));
like image 327
Shane Avatar asked Mar 15 '19 06:03

Shane


People also ask

How do you retrieve data from Firebase in React JS?

Firebase data is retrieved by either a one time call to GetValueAsync() or attaching to an event on a FirebaseDatabase reference. The event listener is called once for the initial state of the data and again anytime the data changes.

How do I save and recover data from Firebase?

Go to the Firebase Console, select your project and click on the Database tab. Scroll down and you will find a Realtime Database section. Click on Create database, select the Start in test mode option and then click Enable.


1 Answers

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.

like image 163
Raj Saraogi Avatar answered Oct 12 '22 09:10

Raj Saraogi