How do i write into my firebase inside useEffect hook?

Viewed 63

this is my code:

 useEffect(() => {
    var firebaseConfig = {
      apiKey: "AIzaSyCn1Sm8P-pgmsHe-n3iLD52LMk0ovTk2J0",
      authDomain: "silkymarket-6036a.firebaseapp.com",
      projectId: "silkymarket-6036a",
      storageBucket: "silkymarket-6036a.appspot.com",
      messagingSenderId: "463420618338",
      appId: "1:463420618338:web:e817961bc3a14c4ca8c33b",
      measurementId: "G-Q1K9YCB91M",
    };
    // Initialize Firebase
    firebase.initializeApp(firebaseConfig);
    initializer.database().ref("users/0401").set({
      name: "dennos karuga",
      age: 21,
    });
  }, []);

it seems firebase is not initializing properly as it needs some sort of async function, i can do the async function when i want to fetch from a given api url but i cant figure out how to do it when im using firebase. kindly help

1 Answers

You can follow the below approach:

1.You can write the initialization code in a particular file and then export it.

firebase.js

 import * as firebase from 'firebase'

 const firebaseConfig = {
      apiKey: "AIzaSyCn1Sm8P-pgmsHe-n3iLD52LMk0ovTk2J0",
      authDomain: "silkymarket-6036a.firebaseapp.com",
      projectId: "silkymarket-6036a",
      storageBucket: "silkymarket-6036a.appspot.com",
      messagingSenderId: "463420618338",
      appId: "1:463420618338:web:e817961bc3a14c4ca8c33b",
      measurementId: "G-Q1K9YCB91M",
    };   // Initialize Firebase   firebase.initializeApp(firebaseConfig);

  export default firebase;

2.Now you can use it whenever you want in the project as below,

import firebase from './firebase';

firebase.database().ref("users/0401").set({
  name: "dennos karuga",
  age: 21,
});
Related