DEV Community

Karthikeyan
Karthikeyan

Posted on

Read and Write using firebase(realtime database) in React JS

Hi everyone,
here i am going to show you how to use firebase in react js

First install firebase

npm i firebase
Enter fullscreen mode Exit fullscreen mode

create config file

import "firebase/auth";
import "firebase/database";
import { initializeApp } from 'firebase/app';
import { getDatabase } from "firebase/database";

const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUT_AUTH_DOMAIN",
  databaseURL: "YOUR_DATABASE_URL",
  projectId: "YOUR_PROJECT_ID",
  storageBucket: "YOUR_STORAGE_BUCKET",
  messagingSenderId: "YOUR_MESSENGER_SENDER_ID",
  appId: "YOUR_APP_ID"
};

// Initialize Firebase
export const app = initializeApp(firebaseConfig);
export const database = getDatabase(app);
Enter fullscreen mode Exit fullscreen mode

if you don't know how to download this config go to this link Firebase web-setup

function for store new data

function writeData() {
    const db = getDatabase();
    const postListRef = ref(db, 'users/'); //
    const newPostRef = push(postListRef);
    set(newPostRef, {
      username: item,
    });
  }
Enter fullscreen mode Exit fullscreen mode

Image description

function for delete data

const Deletedata = (e) => {
    const db = getDatabase();
    remove(ref(db, `users/${e.key}`));
  }
Enter fullscreen mode Exit fullscreen mode

code for fetch data

const Ref = ref(database, 'users/',);

  useEffect(() => {
    onValue(Ref, (snapshot) => {
      const data = snapshot.val();
    });
  }, [])
Enter fullscreen mode Exit fullscreen mode

Enter fullscreen mode Exit fullscreen mode

Top comments (0)