0

I am kind of new in React. I have been able to read real-time data in json format from Firebase in a Web App, but, when I try to write info from the UI to the database I just get code type objects and not the written data. Worst than that, I am messing something else in the code because every time user writes a character, the app updates the value and sends the info to the database. I would deeply appreciate any indication for the right path and thanks in advance.

This is the main page code where the problem occurs:

import React, { Component } from "react";
import {
  IonPage,
  IonContent,
  IonHeader,
  IonToolbar,
  IonButton,
  IonInput,

} from "@ionic/react";
import TabContainer from "../components/TabContainer";
import firebase from '@firebase/app'

const writeUserData =(userInfo)=> {
  firebase.database().ref('reservas').push({
      userInfo
  }).catch((error)=>{
      //error callback
      console.log('error ' , error)
  })
}

class HomePage extends Component {

  constructor() {
    super();
    this.state = {
      onListPage: true,
      username:[],
      reservas:[]

    };
  }

  componentWillUpdate () {

      const readUsersData = ()=> {
      const nameRef =  firebase.database().ref('reservas')
      nameRef.on('value', (snapshot)=> {
        const state = snapshot.val()
        this.state.reservas =  state
    })

    }
    readUsersData()
    }

  _changedTabs = e => {
    if (e.currentTarget.attributes.tab.value === "tab1") {
      this.setState(() => ({ onListPage: true }));
    } else {
      this.setState(() => ({ onListPage: false }));
    }
  }

  render() {

  const myData = this.state.reservas
  const pushData = (username)  => {
    this.setState({username })
    }

    const user = this.state.username

    return (
      <IonPage>
        <IonHeader>
          <IonToolbar color="primary">

          </IonToolbar>
        </IonHeader>
        <IonContent>
          <TabContainer
            history={this.props.history}
            changedTabs={e => this._changedTabs(e)}
            addItem={this._addItem}
            showAddItemModal={this.state.showAddItemModal}
          />
         </IonContent>

        <IonContent> <li> {JSON.stringify({myData})} </li></IonContent>
        <h1>Introduzca la reserva a confirmar:</h1>
        <IonContent>

          <input 
          onChange= {pushData}
           > 
          </input>  

        <IonButton

         onClick={writeUserData( JSON.stringify(user) )}

         > Escribir </IonButton> 
          <IonButton
         onClick={
          send => pushData(send)     
         }
         > Enviar </IonButton> 

         <IonInput/>
         </IonContent>
      </IonPage>
    );
  }
}

export default HomePage


The entire repository is in: https://github.com/progamandoconro/ReactNativeApps/tree/master/Firebase/WebAdmin/src. Thank you.

1 Answer 1

1

So 2 problems here...

  1. The onChange for an input results in an event. You need to extract the value from the event.
  2. You are pushing onChange instead of when the user is done writing. So use onBlur instead or a button press. This will only send when the leave focus on the input. That means you should add a state value to store the value as they type before sending. See below:

import React, { Component } from "react";
import {
  IonPage,
  IonContent,
  IonHeader,
  IonToolbar,
  IonButton,
  IonInput,

} from "@ionic/react";
import TabContainer from "../components/TabContainer";
import firebase from '@firebase/app'

const writeUserData =(userInfo)=> {
  firebase.database().ref('reservas').push({
      userInfo
  }).catch((error)=>{
      //error callback
      console.log('error ' , error)
  })
}

class HomePage extends Component {

  constructor() {
    super();
    this.state = {
      onListPage: true,
      username:[],
      reservas:[],
      value: '',

    };
  }

  componentWillUpdate () {

      const readUsersData = ()=> {
      const nameRef =  firebase.database().ref('reservas')
      nameRef.on('value', (snapshot)=> {
        const state = snapshot.val()
        this.state.reservas =  state
    })

    }
    readUsersData()
    }

  _changedTabs = e => {
    if (e.currentTarget.attributes.tab.value === "tab1") {
      this.setState(() => ({ onListPage: true }));
    } else {
      this.setState(() => ({ onListPage: false }));
    }
  }

  render() {

  const myData = this.state.reservas
  const pushData = (username)  => {
    this.setState({username })
    }

    const user = this.state.username

    return (
      <IonPage>
        <IonHeader>
          <IonToolbar color="primary">

          </IonToolbar>
        </IonHeader>
        <IonContent>
          <TabContainer
            history={this.props.history}
            changedTabs={e => this._changedTabs(e)}
            addItem={this._addItem}
            showAddItemModal={this.state.showAddItemModal}
          />
         </IonContent>

        <IonContent> <li> {JSON.stringify({myData})} </li></IonContent>
        <h1>Introduzca la reserva a confirmar:</h1>
        <IonContent>

          <input 
            onChange={e=>this.setState({value: e.target.value})}
            value={this.state.value}
            onBlur={()=>pushData(this.state.value)}
           > 
          </input>  

        <IonButton

         onClick={writeUserData( JSON.stringify(user) )}

         > Escribir </IonButton> 
          <IonButton
         onClick={
          send => pushData(send)     
         }
         > Enviar </IonButton> 

         <IonInput/>
         </IonContent>
      </IonPage>
    );
  }
}

export default HomePage

Sign up to request clarification or add additional context in comments.

2 Comments

Only one detail, had to change e=>this.setState({value: event.target.value }) for e=>this.setState({value: e.target.value}). Thanks a lot. This is great.
I edited this answer to perfectly solve my problem. Thank you @ageoff.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.