React and Firebase Tutorial: Build a CRUD Notes App

React and Firebase Tutorial: Build a CRUD Notes App

Share It With Your Firends:

Introduction

Are you looking to create a feature-rich note-taking app that allows you to effortlessly manage your thoughts and ideas? Look no further! In this tutorial, we will walk you through the process of building a powerful Note App using React and Firebase. By following this step-by-step guide, you’ll gain hands-on experience in integrating React with Firebase, enabling you to create a dynamic web application with real-time updates.

Setting Up Firebase

Before diving into the development process, we need to set up Firebase for our Note App. It’s a breeze! Start by importing the necessary functions from Firebase SDKs and initializing your app with the provided Firebase configuration. This establishes a seamless connection between your app and Firebase services, laying the foundation for an efficient data management system.

firebase-config.jsx:

// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import {getFirestore} from "firebase/firestore";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app's Firebase configuration
const firebaseConfig = {
  /* config here */
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
export const db = getFirestore(app);

Creating the Note Component

Our first order of business is building the Note component. This component serves as the heart of our app, responsible for creating, displaying, and managing notes. By leveraging the power of React’s state and effect hooks, we’ll seamlessly fetch and update data from Firebase’s Firestore database, providing a smooth and responsive user experience.

  • Adding New Notes – Now, let’s enable users to add new notes to their collection. We’ll create a form that captures the title and content of the note. When the user submits the form, we’ll leverage the addDoc function to store the new note in the Firestore database. This ensures that the note is immediately available for viewing and editing across all devices.

Note.jsx

import React from 'react'
import DisplayNote from './DisplayNote';
import { useState } from 'react';
import { useEffect } from 'react';
import { collection, getDocs, addDoc, deleteDoc, doc, updateDoc } from 'firebase/firestore';
import { db } from '../firebase-config';

const Note = () => {
  const [notes, setNotes] = useState([])
  const [addNote, setAddNote] = useState({ title: "", content: "" })
  const [id, setId] = useState("")

  const noteRef = collection(db, "note")

  useEffect(() => {
    const getNotes = async () => {
      const data = await getDocs(noteRef)
      // console.log(data);
      setNotes(data.docs.map((docs) => ({ ...docs.data(), id: docs.id })))
    }
    getNotes()
  }, [noteRef])

  const handleChange = (e) => {
    const name = e.target.name;
    const value = e.target.value;
    setAddNote({ ...addNote, [name]: value })
  }

  const handleSubmit = async (e) => {
    e.preventDefault()
    // console.log(addNote);
    await addDoc(noteRef, addNote)
  }

  const deleteNote = async (id) => {
    // console.log(id);
    const deletenote = doc(noteRef, id)
    await deleteDoc(deletenote)
  }

  const updateNote = async (note) => {
    // console.log(note);
    setAddNote({title: note.title, content: note.content})
    setId(note.id)
  }

  const updatedNote = async (id) =>{
    console.log(id);
    const updatenote = doc(db, "note", id)
    await updateDoc(updatenote, addNote)
  }

  return (
    <div className="container">

      <form method='post' onSubmit={handleSubmit}>
        <input type="text" name="title" placeholder="Enter Title..." onChange={handleChange} value={addNote.title} required/>
        <textarea name="content" placeholder='Type Content Here...' onChange={handleChange} value={addNote.content} rows="4" required></textarea>
        <div style={{ "display": "flex" }}>
          <button type='submit'>submit</button>
          <button style={{marginLeft: "10px"}} type='button' onClick={()=>updatedNote(id)}>update</button>
        </div>
      </form>

      <div className='note-container'>
        {notes && notes.map((note) => (
          <DisplayNote title={note.title} content={note.content} id={note.id} getId={deleteNote} getUpdateNoteId={updateNote} />
        ))}
      </div>
    </div>
  )
}

export default Note;

Fetching Data from Firebase Firestore

We’ll use the Firestore collection and getDocs function to retrieve the existing notes from the database. By mapping the returned data to the state, we ensure that the notes are displayed in real-time and kept up-to-date.

  • Deleting Notes – To allow users to delete notes, we’ll create a deleteNote function that targets the specific note by its ID in the Firestore database. By utilizing the deleteDoc function, we can remove the note from the database, resulting in the note disappearing from the app’s interface.
  • Updating Notes – Users should be able to edit and update their notes. We’ll implement an updateNote function that sets the note’s content and title to the values of the selected note. By clicking the update button, the updatedNote function will use the updateDoc function to save the changes to the Firestore database.

DisplayNote.jsx

import React from 'react'

const DisplayNote = (props) => {

  const handleClick = (id) =>{
    props.getId(id)
  }

  const handleUpdate = (note) =>{
    props.getUpdateNoteId(note)
  }



  return (
    <div className="note" key={props.id}>
        <p className="title">{props.title}</p>
        <p className="content">{props.content}</p>
        <button onClick={()=>handleClick(props.id)}>delete</button>
        <button style={{"marginLeft": "10px"}} onClick={()=>handleUpdate({content: props.content, title: props.title, id: props.id})}>update</button>
      </div>
  )
}

export default DisplayNote;

By mastering this tutorial, you’ve taken a significant step towards becoming a proficient web developer. Remember to explore the provided code snippets and resources to deepen your understanding of React and Firebase. Now, you can confidently build your own web applications and harness the power of real-time data updates.

Start creating and organizing your thoughts with this powerful Note App built with React and Firebase. Take charge of your productivity and stay organized with ease.

Share It With Your Friends

Leave a Reply

Recent Posts

  • All Post
  • A.I.
  • AI
  • c
  • c++
  • computer
  • cryptocurrency
  • database
  • digital marketing
  • finance
  • hacking
  • HTML
  • java
  • Marketing
  • network
  • other
  • programming
  • python
  • react
  • social
  • Tools
  • Uncategorized
  • web devlopment
    •   Back
    • drawing In Python
DIY AI Voice Assistant In Python

September 8, 2023

Build your own AI assistant with Python! Learn to recognize voice commands, generate responses, and more. Create your virtual companion…

share it

Recent Posts

  • All Post
  • A.I.
  • AI
  • c
  • c++
  • computer
  • cryptocurrency
  • database
  • digital marketing
  • finance
  • hacking
  • HTML
  • java
  • Marketing
  • network
  • other
  • programming
  • python
  • react
  • social
  • Tools
  • Uncategorized
  • web devlopment
    •   Back
    • drawing In Python

Additional Content

CodeWithAM

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus luctus.

Products

Automated Chatbot

Data Security

Virtual Reality

Communication

Support

Services

FAQ's

Privacy Policy

Terms & Condition

Team

Contact Us

Company

About Us

Services

Features

Our Pricing

Latest News

© 2023 Codewitham