最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - ReactJS app authentication: Firebase+FirebaseUI Uncaught Error: Firebase App named '[DEFAULT]-firebaseui-te

programmeradmin1浏览0评论

I'm having trouble with my code. I'm building a one page web app in ReactJS with 3 tabs.

When the user goes to one tab, the authentication form from FirebaseUI should show up. The thing is that it's working only the first time and the second time, if I change to another tab and e back, it crashes, React re-renders the ponent that renders the div with the authentication form and throws the error:

"firebase.js:26 Uncaught Error: Firebase App named '[DEFAULT]-firebaseui-temp' already exists."

My index.html is :

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" href="./src/favicon.ico">
    <script src=".4.1/firebase.js"></script>
    <script>
      // Initialize Firebase
      var config = {
        apiKey: "AIzaSyAdyeoTYNF0xLK37Zv3nEGHWCKNPQjSPsI",
        authDomain: "xxxx",
        databaseURL: "xxxxx",
        storageBucket: "xxxxxx.appspot",
        messagingSenderId: "xxxxxx"
      };
      firebase.initializeApp(config);
    </script>

    <script src=".5/firebase-ui-auth.js"></script>
    <link type="text/css" rel="stylesheet" href=".5/firebase-ui-auth.css" />
        <title>Flockin</title>
   </head>
  <body>

    <div id="root" class="container"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start` in this folder.
      To create a production bundle, use `npm run build`.
    -->

  </body>
</html>

The module that has the Firebase code and fills the div is on another file on a modules directory:

var firebase=global.firebase;
var firebaseui=global.firebaseui;

var  FirebaseUIManager=function(){

// FirebaseUI config.
var uiConfig = {
  'signInSuccessUrl': '/archive',
  'signInOptions': [
    // Leave the lines as is for the providers you want to offer your users.
    firebase.auth.FacebookAuthProvider.PROVIDER_ID,
    firebase.auth.EmailAuthProvider.PROVIDER_ID
  ],
  // Terms of service url.
  'tosUrl': '<your-tos-url>',
};

// Initialize the FirebaseUI Widget using Firebase.
var ui = new firebaseui.auth.AuthUI(firebase.auth());
// The start method will wait until the DOM is loaded.
ui.start('#firebaseui-auth-container', uiConfig);

var initApp = function() {
 firebase.auth().onAuthStateChanged(function(user) {
   if (user) {
     // User is signed in.
     var displayName = user.displayName;
     var email = user.email;
     var emailVerified = user.emailVerified;
     var photoURL = user.photoURL;
     var uid = user.uid;
     var providerData = user.providerData;
     user.getToken().then(function(accessToken) {
       document.getElementById('sign-in-status').textContent = 'Signed in';
       document.getElementById('sign-in').textContent = 'Sign out';
       document.getElementById('account-details').textContent = JSON.stringify({
         displayName: displayName,
         email: email,
         emailVerified: emailVerified,
         photoURL: photoURL,
         uid: uid,
         accessToken: accessToken,
         providerData: providerData
       }, null, '  ');
     });
   } else {
     // User is signed out.
     document.getElementById('sign-in-status').textContent = 'Signed out';
     document.getElementById('sign-in').textContent = 'Sign in';
     document.getElementById('account-details').textContent = 'null';
   }
 }, function(error) {
   console.log(error);
 });
};

initApp();

};

export default FirebaseUIManager;

And finally, the ponent that re-renders the form every time I go back to the tab on the ponentDidMount method is:

import React, { Component } from 'react';
import FirebaseUIManager from './../modules/firebase-auth-login-manager.js';

class FlockinList extends Component {
  ponentDidMount(){
  FirebaseUIManager();
  }

  render() {

    return (
      <div>
         <div id="firebaseui-auth-container"></div>
         <div id="sign-in-status"></div>
         <div id="sign-in"></div>
         <div id="account-details"></div>
      </div>
    );
  }
}

export default FlockinList;

Any idea on how to solve this? Thanks!

I'm having trouble with my code. I'm building a one page web app in ReactJS with 3 tabs.

When the user goes to one tab, the authentication form from FirebaseUI should show up. The thing is that it's working only the first time and the second time, if I change to another tab and e back, it crashes, React re-renders the ponent that renders the div with the authentication form and throws the error:

"firebase.js:26 Uncaught Error: Firebase App named '[DEFAULT]-firebaseui-temp' already exists."

My index.html is :

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" href="./src/favicon.ico">
    <script src="https://www.gstatic./firebasejs/3.4.1/firebase.js"></script>
    <script>
      // Initialize Firebase
      var config = {
        apiKey: "AIzaSyAdyeoTYNF0xLK37Zv3nEGHWCKNPQjSPsI",
        authDomain: "xxxx.",
        databaseURL: "xxxxx.",
        storageBucket: "xxxxxx.appspot.",
        messagingSenderId: "xxxxxx"
      };
      firebase.initializeApp(config);
    </script>

    <script src="https://www.gstatic./firebasejs/ui/live/0.5/firebase-ui-auth.js"></script>
    <link type="text/css" rel="stylesheet" href="https://www.gstatic./firebasejs/ui/live/0.5/firebase-ui-auth.css" />
        <title>Flockin</title>
   </head>
  <body>

    <div id="root" class="container"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start` in this folder.
      To create a production bundle, use `npm run build`.
    -->

  </body>
</html>

The module that has the Firebase code and fills the div is on another file on a modules directory:

var firebase=global.firebase;
var firebaseui=global.firebaseui;

var  FirebaseUIManager=function(){

// FirebaseUI config.
var uiConfig = {
  'signInSuccessUrl': '/archive',
  'signInOptions': [
    // Leave the lines as is for the providers you want to offer your users.
    firebase.auth.FacebookAuthProvider.PROVIDER_ID,
    firebase.auth.EmailAuthProvider.PROVIDER_ID
  ],
  // Terms of service url.
  'tosUrl': '<your-tos-url>',
};

// Initialize the FirebaseUI Widget using Firebase.
var ui = new firebaseui.auth.AuthUI(firebase.auth());
// The start method will wait until the DOM is loaded.
ui.start('#firebaseui-auth-container', uiConfig);

var initApp = function() {
 firebase.auth().onAuthStateChanged(function(user) {
   if (user) {
     // User is signed in.
     var displayName = user.displayName;
     var email = user.email;
     var emailVerified = user.emailVerified;
     var photoURL = user.photoURL;
     var uid = user.uid;
     var providerData = user.providerData;
     user.getToken().then(function(accessToken) {
       document.getElementById('sign-in-status').textContent = 'Signed in';
       document.getElementById('sign-in').textContent = 'Sign out';
       document.getElementById('account-details').textContent = JSON.stringify({
         displayName: displayName,
         email: email,
         emailVerified: emailVerified,
         photoURL: photoURL,
         uid: uid,
         accessToken: accessToken,
         providerData: providerData
       }, null, '  ');
     });
   } else {
     // User is signed out.
     document.getElementById('sign-in-status').textContent = 'Signed out';
     document.getElementById('sign-in').textContent = 'Sign in';
     document.getElementById('account-details').textContent = 'null';
   }
 }, function(error) {
   console.log(error);
 });
};

initApp();

};

export default FirebaseUIManager;

And finally, the ponent that re-renders the form every time I go back to the tab on the ponentDidMount method is:

import React, { Component } from 'react';
import FirebaseUIManager from './../modules/firebase-auth-login-manager.js';

class FlockinList extends Component {
  ponentDidMount(){
  FirebaseUIManager();
  }

  render() {

    return (
      <div>
         <div id="firebaseui-auth-container"></div>
         <div id="sign-in-status"></div>
         <div id="sign-in"></div>
         <div id="account-details"></div>
      </div>
    );
  }
}

export default FlockinList;

Any idea on how to solve this? Thanks!

Share Improve this question edited Sep 28, 2016 at 13:28 Juan L asked Sep 28, 2016 at 1:43 Juan LJuan L 1,7312 gold badges31 silver badges44 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

You should not initialize a new FirebaseUI instance each time you show it:

var ui = new firebaseui.auth.AuthUI(firebase.auth());

This should be initialized externally. If you wish to render, call

ui.start('#firebaseui-auth-container', uiConfig);

When you want to remove, call:

ui.reset();

But do not initialize a new instance each time.

you could use the useEffect hook to make sure the auth container is loaded when the start method is called :

useEffect(() => {
    let ui = new firebaseui.auth.AuthUI(firebase.auth());
    ui.start("#firebaseui-auth-container", uiConfig);
    return () => {
      ui.delete();
    };
  }, []);

remove the instance on unmounting.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论