0

I am in the process of implementing user authentication in my ReactJS app using Firebase using this tutorial: https://www.robinwieruch.de/complete-firebase-authentication-react-tutorial/

Previously I was getting a length is undefined, which was resolved thanks to removing the check of the length of apps when initializing firebase. However now I am now getting firebase.initializeApp is not a function error. enter image description here

The only other similar error I have found is in nodeJS, however the solution was just a typo. firebase.intializeApp is not a function

I have removed all excess steps for accessing the methods supplied by firebase and am now just using those available directly from firebase. (See version history of post.)

My current code set up is as follows:

Register.js

import React, { PropTypes, Component } from 'react';
import Button from 'react-bootstrap/lib/Button';
import Panel from 'react-bootstrap/lib/Panel';
import { auth } from 'firebase';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Register.css';
import history from '../../core/history';
import Background from '../login/loginBackground.jpg';

const sectionStyle = {
  width: '100%',
  height: '900px',
  backgroundImage: `url(${Background})`,
};

const title = 'Register';

const INITIAL_STATE = {
  username: '',
  email: '',
  passwordOne: '',
  passwordTwo: '',
  error: null,
};
// the key value is used as dynamic key to allocate the actual value in the local state object.
const byPropKey = (propertyName, value) => () => ({
  [propertyName]: value,
});

class Register extends Component {
  constructor(props, context) {
    super(props);
    this.state = { ...INITIAL_STATE };
    context.setTitle(title);
  }
  onSubmit = (event) => {
    const {
      username,
      email,
      passwordOne,
    } = this.state;
      //**changed to access methods directly from firebase**
    auth().createUserWithEmailAndPassword(email, passwordOne)
      .then(authUser => {
        // success: set state of fields to INITIAL_STATE (clear fields)
        this.setState(() => ({ ...INITIAL_STATE }));
      })
      .catch(error => {
        // failure: show error in form
        this.setState(byPropKey('error', error));
      });
    // prevent browser reload
    event.preventDefault();
  };

  render() {
    const {
      username,
      email,
      passwordOne,
      passwordTwo,
      error,
    } = this.state;
    // validate fields for same passwords, empty fields etc.
    const isInvalid =
    passwordOne !== passwordTwo ||
    passwordOne === '' ||
    email === '' ||
    username === '';
    return (
      <section style={sectionStyle}>
        <div className="col-md-4 col-md-offset-4">
          <div className="text-center">
            <h1 className="login-brand-text">Register Now!!</h1>
          </div>
          <Panel header={<h3>Please Register</h3>} className="registration-panel">
            <form onSubmit={this.onSubmit}>
              <div className="form-group">
                <input
                  className="form-control"
                  value={username}
                  onChange={event => this.setState(byPropKey('username', event.target.value))}
                  type="text"
                  placeholder="Full Name"
                />
              </div>
              <div className="form-group">
                <input
                  className="form-control"
                  value={email}
                  onChange={event => this.setState(byPropKey('email', event.target.value))}
                  type="text"
                  placeholder="Email Address"
                />
              </div>
              <div className="form-group">
                <input
                  className="form-control"
                  value={passwordOne}
                  onChange={event => this.setState(byPropKey('passwordOne', event.target.value))}
                  type="password"
                  placeholder="Password"
                />
              </div>
              <div className="form-group">
                <input
                  className="form-control"
                  value={passwordTwo}
                  onChange={event => this.setState(byPropKey('passwordTwo', event.target.value))}
                  type="password"
                  placeholder="Confirm Password"
                />
              </div>
              <div className="form-group">
                <Button
                  type="button"
                  disabled={isInvalid}
                  bsSize="sm"
                  bsStyle="success"
                  type="submit"
                >
                  Sign Up
                </Button>
              </div>
              { error && <p>{error.message}</p> }
            </form>
          </Panel>
        </div>
      </section>
    );
  }
 }

Register.contextTypes = { setTitle: PropTypes.func.isRequired };

export default withStyles(s)(Register);

index.js

import * as firebase from 'firebase';
import { firebaseConfig } from './config';

firebase.initializeApp(firebaseConfig);

config.js

export const firebaseConfig = {
    apiKey: "API_KEY",
    authDomain: "AUT_DOMAIN",
    databaseURL: "DATABASE_URL",
    projectId: "PROJECT_ID",
    storageBucket: "STORAGE_BUCKET",
    messagingSenderId: "SENDER_ID"
}

Any help would be greatly, greatly appreciated.

1
  • did you find any solution? it seems i have the same problem. Commented Aug 10, 2018 at 13:34

4 Answers 4

6

I encountered the same error. All you have to do change this line:

firebase.initializeApp(firebaseConfig);

To this:

firebase.default.initializeApp(firebaseConfig); 
Sign up to request clarification or add additional context in comments.

2 Comments

dang it was that simple, can you explain why its that way?
however if i add import "firebase/analytics"; the build fails with [!] Error: 'openDb' is not exported by node_modules/idb/build/idb.js
2

In your Firebase file change this line:

if (!firebase.apps.length) { firebase.initializeApp(config); }

To just this:

firebase.initializeApp(config)

You are only initializing one app per instance of your app, even if you check for development or production you are still using one and not both at the same time so no need to check the length of apps.

Also you got that error because firebase.apps was 'undefined' as you didn't initialize any app yet, so you were not able to check the length of undefined.

You could also implement it this way:

if (firebase.apps === undefined) { firebase.initializeApp(config); }

7 Comments

thank you for your reply. I have edited Firebase file and removed the check for length of apps. However I am now getting that initializeApp is not a function error. Please see updated original post where I have now included Firebase.js and Auth.js
Try initialising the app in your index.js, it must be the first line of code at the very top of your entry file: gist.github.com/alxsnchez/2c25569b36a8220916342bd6b62cf136
Then you can access auth by just import { auth } from 'firebase' and calling it like auth() and the method you want to use, there's no need of doing an extra step with all that "doCreate" stuff... just use the methods firebase gives you upfront
Hi, I have updated to use your solution and gotten rid of the excess steps , however I am still getting the same error. Perhaps I haven't fully understood what you meant for your solution? I have edited my initialization to suit your github link and I have changed how I called the createUser method in Register.js. Thank you very much for your time and help
Can you upload your project somewhere I can have a look in deep and debug it?
|
1

You should still check the length because Firebase tries to create new instance with the exact same config which it can not do and throws an error. Also, keep in mind that Firebase 8 introduced some breaking changes: https://firebase.google.com/support/release-notes/js#version_800_-_october_26_2020

Now you can make it work like this if you use .default:

const firebase = require('firebase/app').default

if (!firebase.apps.length) {
    firebase.initializeApp(firebaseConfig)
}

Comments

0

You should check auth.js file where you are considering a length of the array. but that array variable is not defined. If you couls post auth.js. An error picture doesn't tell much about the location.

1 Comment

I have updated to include both auth.js and firebase.js, thanks

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.