Advait
Advait

Reputation: 13

Having problems uploading react form data to firebase

I have made a react form that sores the input values in variables. I have checked and the error is not in the values themselves but purely in the uploading process. Please help. I am not getting any errors, it just isn't working. I have all the necessary firebase data stored in firebase.js.

import React, { Component} from 'react';
import logo from './logo.svg';
import {Link, BrowserRouter as Router, Switch, Redirect} from 'react-dom';
import App from './App';
import './profile.css'
import firebase from './firebase'

class Profile extends Component{

    state = {
        name: "",
        age: "",
    }

    handleInput = event => {
        this.setState({[event.target.name] : event.target.value});
    }
    uploadValues = event => {
        firebase
            .firestore()
            .collection('user1')
            .add({
                name: this.state.name,
                age: this.state.age,
            });
            alert('Data uploaded');
    }
    logValues = () => {
        alert(this.state.name);
        alert(this.state.age);
        this.uploadValues();
    }
    render(){
        return(
            <div className="container">
                <h1>Update your Profile here</h1>
                <form className="profileForm">
                    <input type = "text" id="nameInput" placeholder="Full Name" onChange = 
{this.handleInput} name = "name"/>
                    <input type = "number" id="birthdate" placeholder="Age" onChange = 
{this.handleInput} name = "age" />
                    <button type = "submit" onClick={this.logValues} id="saveChanges" >Save 
Changes</button>
                </form>
            </div>
        );
    }
}
export default Profile;

Upvotes: 0

Views: 64

Answers (1)

Zeitgeist
Zeitgeist

Reputation: 101

add function returns a promise, therefore the process itself is not being executed.

Convert your function to asynchronous or add a then() to the returned promise:

uploadValues = async () => {
    await firebase
        .firestore()
        .collection('user1')
        .add({
            name: this.state.name,
            age: this.state.age,
        });
    alert('Data uploaded');
}

Executing your promise:

uploadValues = () => {
    firebase
        .firestore()
        .collection('user1')
        .add({
            name: this.state.name,
            age: this.state.age,
        }).then(() => {
            alert('Data uploaded');
        }).catch((err) => alert(err);
}

Upvotes: 2

Related Questions