DEV Community

Cover image for Crud operation: React + Firebase Realtime Database
chen sokheng
chen sokheng

Posted on • Edited on

Crud operation: React + Firebase Realtime Database

In this article I am going to build a simple todo to demonstrate how to do crud with React and Firebase Realtime database..
There is a video tutorial as well here is the link: https://youtu.be/v0TKYSkZ2tI

Config firebase

  1. go to firebase
    • choose go to console and create a new project
    • choose this one

Alt Text

  • copy this Alt Text
    • choose realtime database Alt Text
    • select test mode Alt Text
    • Install firebase to your project
      npm i firebase
Enter fullscreen mode Exit fullscreen mode

util/firebase.js

import firebase from firebase
const firebaseConfig = {
    apiKey: "AIzaSyCzRUkmetmwFrEqvL-HMZNuWRFq3rUMs-4",
    authDomain: "hello-c7e7a.firebaseapp.com",
    databaseURL: "https://hello-c7e7a.firebaseio.com",
    projectId: "hello-c7e7a",
    storageBucket: "hello-c7e7a.appspot.com",
    messagingSenderId: "1022778008563",
    appId: "1:1022778008563:web:791884b13e82f5a64de886",
    measurementId: "G-QDLR4PBRFR"
  };
  // Initialize Firebase
  firebase.initializeApp(firebaseConfig);
  firebase.analytics()
export default firebase;
Enter fullscreen mode Exit fullscreen mode

Component

App.js

import React from 'react';
import './App.css';
import Form from './components/Form';
import TodoList from './components/TodoList';

export default function App() {
  return (
    <div className="App">
      <h1>Todo</h1>
      <Form />
      <TodoList />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Create

components/form.js

import React, { useState } from 'react';
import firebase from '../util/firebase';

export default function Form() {
  const [title, setTitle] = useState('');

  const handleOnChange = (e) => {
    setTitle(e.target.value);
  };
  const createTodo = (){...}
  return (
    <div>
      <input type="text" onChange={handleOnChange} value={title} />
      <button onClick={createTodo}>Add Todo</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

This is how we are going to create todo

  const createTodo = () => {
    const todoRef = firebase.database().ref('Todo');
    const todo = {
      title,
      complete: false,
    };

    todoRef.push(todo);
  };
Enter fullscreen mode Exit fullscreen mode
  • here is our data will look like Alt Text

Read

components/TodoList.js

import React, { useState, useEffect } from 'react';
import firebase from '../util/firebase';
import Todo from './Todo';

export default function TodoList() {
  const [todoList, setTodoList] = useState();

  useEffect(() => {
    const todoRef = firebase.database().ref('Todo');
    todoRef.on('value', (snapshot) => {
      const todos = snapshot.val();
      const todoList = [];
      for (let id in todos) {
        todoList.push({ id, ...todos[id] });
      }
      setTodoList(todoList);
    });
  }, []);

  return (
    <div>
      {todoList
        ? todoList.map((todo, index) => <Todo todo={todo} key={index} />)
        : ''}
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode
  • note here: you use
todoRef.once("value")
// for listen to the data change only one time
Enter fullscreen mode Exit fullscreen mode
todoRef.on("value")
// listen every time data change in todo ref
Enter fullscreen mode Exit fullscreen mode

update and delete

components/Todo.js

import React from 'react';
import firebase from '../util/firebase';
import '../App.css';

export default function Todo({ todo }) {
  return (
    <div>
      <h1 className={todo.complete ? 'complete' : ''}>{todo.title}</h1>
      <button onClick={deleteTodo}>Delete</button>
      <button onClick={completeTodo}>Complete</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

update

  const completeTodo = () => {
    const todoRef = firebase.database().ref('Todo').child(todo.id);
    todoRef.update({
      complete: !todo.complete,
    });
  };
Enter fullscreen mode Exit fullscreen mode

delete

  const deleteTodo = () => {
    const todoRef = firebase.database().ref('Todo').child(todo.id);
    todoRef.remove();
  };
Enter fullscreen mode Exit fullscreen mode

Result

Alt Text

code:
https://github.com/Chensokheng/crud-todo-app

Reference

Top comments (4)

Collapse
 
wseai profile image
jagarkin

how can i make this related to specific user ?

Collapse
 
snangunurikrishna profile image
snangunurikrishna

you have missed

  1. "/" in firebase.database().ref('Todo');
    It should be firebase.database().ref('/Todo');

  2. import firebase from firebase. Here firebase should be in inverted commas
    import firebase from 'firebase'

Collapse
 
hwolf0610 profile image
Harry Naruto

Thank you for your post.
I am very helpful with this blog post.

Collapse
 
yustinayasin profile image
yustinayasin

Thanks for the tutorial