#StackBounty: #reactjs #firebase #firebase-authentication Firebase authentication: how to resolve 'TypeError: Cannot read property …

Bounty: 100

I’m new to implementing auth, and having some confusion about how to resolve an issue I’m having.

I’m building a react app, and want logged in users to be able to submit data via the GigRegister component to a firebase database. However when I try to submit information, I get the following error:


    TypeError: Cannot read property 'getIdToken' of null

Any thoughts on how I can resolve this?

Here’s the code for the login page (which redirects to the gig register page upon login):

import React from 'react'
import Header from './Header'
import Button from '@material-ui/core/Button'
import axios from 'axios'
import {Link} from 'react-router-dom'

class Login extends React.Component {
  constructor() {
    super();
    this.state = {
      email: "",
      password: "",
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(e) {
    this.setState({
      [e.target.name]: e.target.value,
    });
  }

  handleSubmit(e) {
    console.log("submit reached");
    e.preventDefault();
    const loginData = {
      email: this.state.email,
      password: this.state.password,
    };
    axios("http://localhost:5000/gig-fort/us-central1/api/login", {
      method: "POST",
      headers: {
        "content-type": "application/json",
      },
      data: loginData,
    })
      .then((res) => {
        console.log(res.data);
        this.props.history.push("/gigregister");
      })
      .catch((err) => {
        console.error(err);
      });
  }

  render() {
    return (
      <>
        <div>
          <Header />
        </div>
        <Link to="/Homepage" style={{ textDecoration: "none" }}>
          <h1 className="login-header">Gigs this week</h1>
        </Link>
        <div className="login-main">
          <div className="login">
            <h2>Venue login</h2>
            <form onSubmit={this.handleSubmit}>
              <input
                type="text"
                name="email"
                placeholder="email"
                onChange={this.handleChange}
              />
              <br></br>
              <input
                type="password"
                name="password"
                placeholder="password"
                onChange={this.handleChange}
              />
              <div className="button">
                <Button type="submit">Submit</Button>
              </div>
            </form>
          </div>
          <Link to="/venueregister" style={{ textDecoration: "none" }}>
            <h2 style={{ color: "#b49650" }}>Register a venue</h2>
          </Link>
        </div>
      </>
    );
  }
}

export default Login;

..and here’s the gig register page:


    import React from "react";
    import Header from "./Header";
    import TextField from "@material-ui/core/TextField";
    import Button from "@material-ui/core/Button";
    import axios from "axios";
    import * as firebase from 'firebase'
    
    firebase.initializeApp({
        apiKey: "",
        authDomain: "",
        databaseURL: "",
        projectId: "gig-fort",
        storageBucket: "gig-fort.appspot.com",
        messagingSenderId: "",
        appId: ""
    })
    
    
    class GigRegister extends React.Component {
      constructor() {
        super();
        this.state = {
          name: "",
          venue: "",
          time: "",
          date: "",
          genre: "",
          tickets: "",
          price: "",
        };
        this.handleSubmit = this.handleSubmit.bind(this);
        this.handleChange = this.handleChange.bind(this);
      }
    
      handleChange(e) {
        this.setState({
          [e.target.name]: e.target.value,
        });
      }
    
      handleSubmit(e) {
        console.log("submit function reached");
        e.preventDefault();
        const gigData = {
          name: this.state.name,
          venue: this.state.venue,
          time: this.state.time,
          date: this.state.date,
          genre: this.state.genre,
          tickets: this.state.tickets,
          price: this.state.price,
        };
        
    
        firebase.auth().currentUser.getIdToken().then(function(token) {
          axios("http://localhost:5000/gig-fort/us-central1/api/createGigListing", {
            method: "POST",
            headers: {
              "content-type": "application/json",
              "Authorization": "Bearer "+token,
            },
            data: gigData,
          })
      })
          .then((res) => {
            console.log(res.data);
          })
          .catch((err) => {
            console.error(err);
          });
      }
    
    
    
      render() {
        return (
          <div className="gig-register">
            <Header />
            <h1 className="header-gigReg">Register a gig</h1>
            <form onSubmit={this.handleSubmit}>
              <TextField
                placeholder="Event name"
                defaultValue="Event name"
                id="name"
                name="name"
                onChange={this.handleChange}
              />
              <TextField
                placeholder="Venue"
                defaultValue="Venue"
                id="venue"
                name="venue"
                onChange={this.handleChange}
              />
              <TextField
                placeholder="Time"
                defaultValue="Time"
                type="time"
                label="Enter start time"
                id="time"
                name="time"
                InputLabelProps={{
                  shrink: true,
                }}
                inputProps={{
                  step: 300, // 5 min
                }}
                onChange={this.handleChange}
              />
              <TextField
                id="date"
                label="Select date"
                type="date"
                defaultValue="2017-05-24"
                InputLabelProps={{
                  shrink: true,
                }}
                onChange={(e) => {
                  this.setState({ date: e.target.value });
                }}
              />
              <TextField
                placeholder="Genre"
                defaultValue="Genre"
                id="genre"
                name="genre"
                onChange={this.handleChange}
              />
              <TextField
                placeholder="Tickets"
                defaultValue="Tickets"
                id="tickets"
                name="tickets"
                onChange={this.handleChange}
              />
              <TextField
                placeholder="Price"
                defaultValue="Price"
                id="price"
                name="price"
                onChange={this.handleChange}
              />
              <Button type="submit">Submit</Button>
            </form>
          </div>
        );
      }
    }
    
    export default GigRegister

Back end functions:

app.post('/login', (req,res)=> {
    const user = {
        email: req.body.email,
        password: req.body.password
    }
    
    let errors = {}

    if(isEmpty(user.email)){
        errors.email = 'Must not be empty'
    }

    if(isEmpty(user.password)){
        errors.password = 'Must not be empty'
    }

    if(Object.keys(errors).length >0){
        return res.status(400).json(errors)
    }

    firebase.auth().signInWithEmailAndPassword(user.email, user.password)
    .then((data) => {
        return data.user.getIdToken()
    })
    .then(token => {
        return res.json({token})
    })
    .catch(err => {
        if(err.code === 'auth/wrong-password'){
            return res.status(403).json({general: 'Wrong credentials, please try again'})
        }
        return res.status(500).json({error: err.code})
    })
})


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.