Raul Sanchez
Raul Sanchez

Reputation: 2019

How do I render Firestore data in React?

I am fairly new to React and Firebase/Firestore. I have gone through the Firestore docs a few times and still feel lost. Here's what I know how to do... I know how to add to my Firestore DB, and I know how to print data to the console. But I don't know how to render that data? Can anyone please guide me on how to do this? Thanks

import React, { Component } from 'react';
import './App.css';

import { database } from './firebase/firebase';

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      inputField: ''
    };
  }

  onInputChange = (e) => {
    const inputField = e.target.value;
    this.setState(() => ({ inputField }));
  }

  /* Adding Data */
  onSubmit = (e) => {
    e.preventDefault();
    console.log(this.state.inputField);

    database.collection('users').add({
      name: this.state.inputField
    })
    .then((docRef) => {
      console.log("Doc written with ID: ", docRef.id)
    })
    .catch((error) => {
      console.error("Error adding document: ", error);
    });
  }

  /* Retrieving Data */
  onLoad = (e) => {
    const docRef = database.collection('users').doc('O6m4TFfIjE42ZaNfvC7s');

    docRef.get().then((doc) => {
      if (doc.exists) {
        console.log("Document data:", doc.data());
      } else {
        // doc.data() will be undefined in this case
        console.log("No such document!");
      }
      }).catch(function(error) {
        console.log("Error getting document:", error);
      });
  }

  render() {
    return (
      <div className="App">
        <h1>Raul: <p>{}</p></h1>
        <form onSubmit={this.onSubmit}>
          <input 
            type="text" 
            value={this.state.inputField} 
            onChange={this.onInputChange}  
          />
          <button>Save</button>
        </form>
        <button onClick={this.onLoad}>Load Data</button>
      </div>
    );
  }
}

export default App;

Upvotes: 1

Views: 9479

Answers (2)

IjzerenHein
IjzerenHein

Reputation: 2755

Using the Firebase/Firestore API directly in React can be quite cumbersome and lead to a lot of boilerplate. You could use Firestorter, which uses mobx behind the scenes to hook up your components to Firestore within seconds.

https://github.com/IjzerenHein/firestorter

Upvotes: 0

Ali Faris
Ali Faris

Reputation: 18592

you can save the data in the state

constructor(props)
{
    super(props);
    this.state = {
        inputField: '',
        data: null,
    };
}

save the data to state when data loaded

onLoad = (e) => {
    const docRef = database.collection('users').doc('O6m4TFfIjE42ZaNfvC7s');

    docRef.get().then((doc) => {
        if (doc.exists) {
            let data = doc.data();
            this.setState({ data: data });
            console.log("Document data:", data);
        } else {
            // doc.data() will be undefined in this case
            this.setState({ data: null });
            console.log("No such document!");
        }
    }).catch(function (error) {
        this.setState({ data: null });
        console.log("Error getting document:", error);
    });
}

and then render them as you want, I will display them as json in <pre> tag

render() {

    let dataUI = this.state.data ? <h1>No Data</h1> : <pre>{JSON.stringify(this.state.data)}</pre>;

    return (
        <div className="App">
            <h1>Raul: </h1>

            <div>
                <h1>UI Data</h1>
                {dataUI}
            </div>

            <form onSubmit={this.onSubmit}>
                <input
                    type="text"
                    value={this.state.inputField}
                    onChange={this.onInputChange}
                />
                <button>Save</button>
            </form>
            <button onClick={this.onLoad}>Load Data</button>
        </div>
    );
}

Upvotes: 3

Related Questions