将数据保存到Firebase

时间:2019-04-15 11:44:51

标签: reactjs firebase firebase-realtime-database

enter image description here

我正在构建此会议预订应用程序,在该应用程序中,书籍中可用的会议以按钮形式显示,并在您弹奏会议后选择您要的会议。我希望可以使用在表单中编写的名称和电子邮件将该信息保存在按钮中。

我很难设置代码,因此按下提交按钮后,我的按钮选择将与名称和电子邮件一起保存并保存到Firebase。知道我收到handleSubmit中的“设置”未设置的错误。

import React, { Component } from "react";
import "./App.css";
import firebase from "firebase";
const uuid = require("uuid");

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      uid: uuid.v1(),
      meeting: "",
      name: "",
      email: ""
    };

    this.handleClick = this.handleClick.bind(this);
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);

    var config = {
      apiKey: "",
      authDomain: "",
      databaseURL: "",
      projectId: "",
      storageBucket: "",
      messagingSenderId: ""
    };
    firebase.initializeApp(config);
    // console.log(firebase);

    var database = firebase.database();
    var ref = database.ref("meeting");

    var data = {
      id: "",
      user: ""
    };
    ref.push(data);

    // this.state = {
    //  items: [],
    //  isLoaded: true,
    // }

    // this.state = {
    // name: '',
    // email: '',
    // };
  }

  handleClick = e => {
    console.log(e.target.innerHTML);
    alert("Du har valt ett möte");
  };

  componentDidMount() {
    fetch("http://www.mocky.io/v2/5c9cdca03300004d003f2151")
      .then(res => res.json())
      .then(json => {
        let meetings = [];
        json.forEach(meeting => {
          if (
            new Date(meeting.startDate).getDay() !==
            new Date(meeting.endDate).getDay()
          ) {
            let day1 = {
              activity: meeting.activity,
              location: meeting.location,
              startDate: meeting.startDate
            };
            let day2 = {
              activity: meeting.activity,
              location: meeting.location,
              endDate: meeting.endDate
            };

            meetings.push(day1, day2);
          } else {
            meetings.push(meeting);
          }
        });
        console.log(meetings);
        this.setState({
          isLoaded: true,
          items: meetings
        });
      });

    firebase
      .database()
      .ref(`Newdata/${this.state.uid}`)
      .on("value", snap => console.log("from db", snap.val()));
  }

  handleChange(e) {
    this.setState({
      name: e.target.name
    });
  }

  handleSubmit(e) {
    alert("Er bokning är bekräftad: " + this.state.value);
    console.log("Du har bekräftat er bokning");
    e.preventDefault();
    firebase.database().ref(`Newdata/${this.state.uid}`);
    set({
      meeting: this.state.meeting,
      name: this.state.name,
      email: this.state.email
    }).catch(error => console.log(error));
  }

  inputData(e) {
    const meeting = this.refs.meeting1.value;
    const name = this.refs.name1.value;
    const email = this.refs.email1.value;
    this.setState({ meeting, name, email });
  }

  render() {
    var { isLoaded, items } = this.state;

    if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
      return (
        <>
          <div className="App">
            <div className="AppHeader">
              <h1>Boka ditt möte nedan</h1>
            </div>
            <ul>
              {items.map((item, i) => (
                <li key={i}>
                  <button
                    onClick={e => this.handleClick(e)}
                    onChange={this.inputData}
                    className="select"
                  >
                    {item.activity}
                    <br />
                    Starttid: {item.startDate}
                    <br />
                    Sluttid: {item.endDate}
                    <br />
                    Plats: {item.location}
                    <br />
                  </button>
                </li>
              ))}
            </ul>
          </div>

          <div className="selectedMeeting">
            Fyll i dina uppgifter och bekräfta
          </div>

          <form onSubmit={this.handleSubmit} className="bookingSection">
            <label>
              Name:
              <input
                type="text"
                name={this.state.name}
                onChange={this.inputData}
                onChange={this.handleChange}
                ref="name1"
              />
            </label>
            <label>
              E-mail:
              <input
                type="text"
                email={this.state.email}
                onChange={this.inputData}
                onChange={this.handleChange}
                ref="email1"
              />
            </label>
            <input className="confirm" type="submit" value="Bekräfta" />
          </form>
          <div className="viewSelect" />
        </>
      );
    }
  }
}

export default App;

1 个答案:

答案 0 :(得分:0)

TL; DR;

您的代码中有错字,应该是:

firebase.database().ref('Newdata/${this.state.uid}').set({
      meeting: this.state.meeting,
      name: this.state.name,
      email: this.state.email
    }).catch(error => console.log(error));

说明:

添加;后,您将结束第一个表达式并开始一个新的表达式,即:

set({
      meeting: this.state.meeting,
      name: this.state.name,
      email: this.state.email
    }).catch(error => console.log(error));

由于未定义函数,因此Javascript会出现此错误。但是您要做的是调用对象set的方法firebase.database().ref('Newdata/${this.state.uid}'),因此您应该执行以下操作: firebase.database().ref('Newdata/${this.state.uid}').set({ /* ... */ })