-1

I'm trying to make a program, using React and Firebase. I'm getting an error:

Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicate-app).

How can I initialize it only once to get rid of the error? Should I initialize it somewhere else?

My code:

import React from 'react';
import * as firebase from 'firebase';
import "firebase/app";
import "firebase/database";

function Login() {
  var firebaseConfig = {
    ...
  };
  // Initialize Firebase
  firebase.initializeApp(firebaseConfig);
  function verify(){
    var server = firebase.database().ref('servers/' + document.getElementById("code").value);
    server.on('value', function(snapshot) {

      if(snapshot.val() && snapshot.val().exist)
      {
        console.log(snapshot.val()); 
        alert("sucsess");
      } else{
        alert("fail");
      }
    });
  }
  function checkEnter(event) {
    if(event.key === 'Enter') {
      verify(); 
    }
  }


  return (
    <div>
     ...
    </div>
  );
}

export default Login;
Laczkó Örs
  • 1,082
  • 1
  • 18
  • 38
  • hard to tell without context but if i'd guess your Login component is re-rendering at some point and re-initializing the app. maybe try putting your initialization in `componentDidMount` or similar to prevent duplicate calls? – imjared Jul 12 '19 at 21:10
  • How should I do it? – Laczkó Örs Jul 12 '19 at 21:11
  • It seems that you have initialized the APP for Firebase twice. do you have such a thing as `firebase.initializeApp(firebaseConfig)` somewhere else in your app? – Sultan H. Jul 12 '19 at 21:11
  • Nope. But my program breaks when I come back from the SignIn. It's reloading the element, where I initialize firebase. – Laczkó Örs Jul 12 '19 at 21:14

1 Answers1

1

Please replace firebase.initializeApp(firebaseConfig); with:

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

The explanation is the same as I told you in the comment, I hope that would be enough.

Sultan H.
  • 2,908
  • 2
  • 11
  • 23