最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I render Firestore data in React? - Stack Overflow

programmeradmin1浏览0评论

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;

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;
Share Improve this question edited Jan 27, 2018 at 19:39 Raul Sanchez asked Jan 27, 2018 at 19:30 Raul SanchezRaul Sanchez 2,0293 gold badges14 silver badges7 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

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>
    );
}

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 ponents to Firestore within seconds.

https://github./IjzerenHein/firestorter

发布评论

评论列表(0)

  1. 暂无评论