Firebase

Basics of Firebase

Pratik Kabade, 19 October 2022

Firebase is a set of hosting services for any type of application. It offers NoSQL and real-time hosting of databases, content, social authentication, and notifications, or services, such as a real-time communication server.

Content

  1. Get Started
  2. Sign In
  3. Sign Out
  4. Create
  5. View

1 Get Started

install

npx install firebase

dependancies

npx create-react-app my-app

2 Sign In

const navigate = useNavigate();

const signInWithGoogle = async () => {
  const res = await signInWithPopup(auth, provider);
  navigate("/profile");
};

return (
  <>
    <button className='GoogleSignIn' onClick={signInWithGoogle}>
      <img
        src='https://raw.githubusercontent.com/dependabot-pr/Static-Files/main/Assets/Logo/Google.svg'
        alt='google logo'
        className='GLogo'
      />
      <div className='GText'>Sign in with Google</div>
    </button>
  </>
);

3 Sign Out

const navigate = useNavigate();

const signUserOut = async () => {
  signOut(auth);
  navigate("/");
};

return (
  <button onClick={signUserOut} className='nav-link logOutBTN'>
    LogOut
  </button>
);

4 Create

// Form
import { yupResolver } from "@hookform/resolvers/yup";
import { useForm } from "react-hook-form";
import * as yup from "yup";
// IMPORT DB
import { addDoc, collection } from "firebase/firestore";
import { auth, db } from "../../config/firebase";
import { useAuthState } from "react-firebase-hooks/auth";

interface CreatePost {
  title: string;
  description: string;
}

export const CreatePost = () => {
  const schema = yup.object().shape({
    title: yup.string().required(),
    description: yup.string().required("fill description"),
  });

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm <
  CreatePost >
  {
    resolver: yupResolver(schema),
  };

  // GET USER
  const [user] = useAuthState(auth);

  // DATABASE MODIFICATION
  const postRef = collection(db, "posts");

  const onCreatePost = async (data: CreatePost) => {
    await addDoc(postRef, {
      // title: data.title,
      // description: data.description,

      // OR
      ...data,
      username: user?.displayName,
      email: user?.email,
      id: user?.uid,
    });
  };

  // RETRIEVE
  return (
    <div>
      <form onSubmit={handleSubmit(onCreatePost)} className='compart'>
        <input placeholder='Title' {...register("title")} />
        <p>{errors.title?.message}</p>
        <input placeholder='Description' {...register("description")} />
        <p>{errors.description?.message}</p>
        <input type='submit' />
      </form>
    </div>
  );
};

5 View

ViewPost

import { getDocs, collection } from "firebase/firestore"
import { useEffect, useState } from "react"
import { db } from "../../config/firebase"
import { ThePost } from "./ThePost"

export interface Post {
    id: string;
    email: string;
    title: string;
    username: string;
    description: string;
}

export const ViewPost = () => {

  // DATABASE LINK
    const [posts, setPosts] = useState<Post[]>(null);
    const postsRef = collection(db, "posts");

    const getPosts = async () => {
        const data = await getDocs(postsRef)
        setPosts(
            data.docs.map((doc) => ({ ...doc.data(), id: doc.id })) as Post[]
        )
    }

  // REFRESH
    useEffect(() => {
        getPosts();
    }, [])

  // RETRIEVE
    return (
        <div>
            {posts?.map((post) => (
                <ThePost post={post} />
            ))}
        </div>
    )
}

ThePost

import { Post as iPost } from "./ViewPost";

interface Props {
  post: iPost;
}

// SEND
export const ThePost = (props: Props) => {
  const { post } = props;
  return (
    <div className='compart'>
      <p>
        title: <b>{post.title}</b>
      </p>
      <p>
        description: <b>{post.description}</b>
      </p>
      <p>
        username: <b>{post.username}</b>
      </p>
    </div>
  );
};