To-do list with Firebase (Web ver.9)
Tags: react, firebase
Published: 2022-02-12 05:57:30

This is a memo when I create a to-do list which has a feature of user authentication (Demo [here](https://to-do2-f439d9.netlify.app/auth)/ Code [here](https://github.com/Lada496/to-do-list-with-auth-public)).

## Install Firebase into your project folder

### 1. Get started

Sign up Firebase and click “Get started”.

![](https://cdn-images-1.medium.com/max/4512/1*9z-k79tFXYUWaNTTCW7w4w.png)

### 2. Create a project

Click “Add project”

![](https://cdn-images-1.medium.com/max/4504/1*l4hhsIY1o2Jn0Mvuc3VIBQ.png)

### 3. Decide your project name

Enter your project name and click “Continue”

![](https://cdn-images-1.medium.com/max/4464/1*ShyCk-BGvNFhK5dzxNn6iw.png)

### 4. Click “Continue”

![](https://cdn-images-1.medium.com/max/4352/1*7T2oGSLrtqTkNj_szQnWOA.png)

### 5. Choose your account and Click “Create Project”

You can omit this process if you disable Google Analytics.

![](https://cdn-images-1.medium.com/max/4364/1*hczASVOicmU89dz1KmYjMg.png)

### 6. Project is created in a while

Click “Continue” to start your project.

![](https://cdn-images-1.medium.com/max/4380/1*hSUHZVUaB3lWwbbkEzmX4w.png)

### 7. Click “</>” to set up your app

![](https://cdn-images-1.medium.com/max/4408/1*Ua1FsMb8J25o3kCjOB0AwA.png)

### 8. Decide your app nickname

Enter your app name and click “Register app”

![](https://cdn-images-1.medium.com/max/4416/1*wQSxM6yrCS2hjODa_j_bzw.png)

### 9. Obtain a config snippet and an install command.

![](https://cdn-images-1.medium.com/max/4372/1*GbHJNNuypEQcioUD0i6agQ.png)

### 10. install firebase into your local project folder

Go to your project folder and run this command.

    npm install firebase

### 11. Create a config file for firebase app.

Copy the config information you got and paste it in your config file.
```javascript
    // example (assume in config.js)
    export const firebaseConfig = {

    // configuration information

    }
```
### 12. Initialize Firebase where you want to use it

Import initializeApp from firebase/app and firebaseConfig from config.js
```javascript
    // example (assume in App.js and you have config.js)
    import { initializeApp } from "firebase/app"
    import { firebaseConfig } from "./config.js"

    initializeApp(firebaseConfig)

    function App(){
           ...
    }

    export default App;
```
More information is available [here](https://firebase.google.com/docs/web/setup).

## Use Realtime Database

### 1. Go to Realtime Database page

![](https://cdn-images-1.medium.com/max/4392/1*X7vo-hgxRhZRky1yol-tgg.png)

### 2. Click “Create Database”

![](https://cdn-images-1.medium.com/max/4392/1*tNtDEXfaCaU_huPbTKQxXA.png)

### 3. Choose a region and click “Next”

![](https://cdn-images-1.medium.com/max/4384/1*1r3Yya79uQWdGMPwp723kA.png)

### 4. Choose a mode

I chose test mode first to test and changed rules after I added user authentication.

![](https://cdn-images-1.medium.com/max/4388/1*fpWY8c8ULnXTaFT81lh2sA.png)

### 5. Copy the database URL

![](https://cdn-images-1.medium.com/max/4368/1*Q1vdWyV6Ij01grjWYvJEyA.png)

### 6. Add databaseURL in your config.js
```javascript
    export const firebaseConfig = {

    // configuration information
    databaseURL:"https://databaseName.firebaseio.com"

    }

    const app = initializeApp(firebaseConfig);
    export const db = getDatabase(app);
```
### 7. Get a reference to the database service
```javascript
    // example
    import { initializeApp } from 'firebase/app';
    import { getDatabase } from "firebase/database";
    import { db } from "./config.js"
```
Official information about getting start Firebase Realtime Database is provided [here](https://firebase.google.com/docs/database/web/start).

### 8. Read Data

Here is an example to read data from a Realtime database by using onValue and ref (visit [here](https://firebase.google.com/docs/database/web/read-and-write) for more information)
```javascript
    const auth = getAuth();
    const uid = useSelector((state) => state.auth.uid);
    const dbRef = ref(db, `notes/${uid}`);
    const readData = useCallback(() => {
    onValue(dbRef, (*snapshot*) => {
    const data = snapshot.val();
    const loadedList = [];
    for (const key in data) {
    loadedList.push({
    id: key,
    title: data[key].title,
    description: data[key].description,
    });
    }
    setList(loadedList);
    setInit(false);
    });
    }, [dbRef]);
```
### 9. Update Data

This is an example to manipulate an existing database. Here I use update to add another item to the database. You can use set if you want to override your database.
```javascript
    const newPostKey = push(child(ref(db), "notes")).key;
    const updates = {};
    updates[`/notes/${uid}/${newPostKey}`] = item;
    update(ref(db), updates);
    readData();
```
### 10. Delete Data

You can delete a certain data by remove method with providing data path.
```javascript
    // General syntax
    remove(ref(db, path)

    // an example to delete a specific data of a specific user
    remove(ref(db, `notes/${uid}/${id}`));
```
### 11. Manage the database rule

A common way to secure your database is authentication. Here is an example that allows only an authenticated user can read and write her/his data. For more information about security and rules, please visit [here](https://firebase.google.com/docs/database/security).

    {
      "rules": {
        "notes": {
          "$uid": {
            ".read": "$uid === auth.uid"
            ".write": "$uid === auth.uid"

          }
        }
      }
    }

## Use Authentication

### 1. Click “Authentication”

![](https://cdn-images-1.medium.com/max/5716/1*hvkbEB8OQoiqulAjbRaYCw.png)

### 2. Click “Get started”

![](https://cdn-images-1.medium.com/max/5728/1*Tvzj9FR3j_vt1iI8JdyjNA.png)

### 3. Choose method

I used Email/Password for this project.

![](https://cdn-images-1.medium.com/max/5724/1*ZHsRhJ-FK7F41nrdZrHcqA.png)

### 4. Enable Email/Password method and click “Save”

![](https://cdn-images-1.medium.com/max/5720/1*CkVX7SfEgF7zHMsRf6nebA.png)

Then you will see this page. Official information is available [here](https://firebase.google.com/docs/auth/web/start).

![](https://cdn-images-1.medium.com/max/5692/1*A0ciIbthvxL0dY-JrD402Q.png)

### 5. Add sign up feature

Use createUserWithEmailAndPassword.
```javascript
    // an example
    import { getAuth, createUserWithEmailAndPassword } from "firebase/auth";
    
    const auth = getAuth();
    const [email, setEmail] = useState()
    const [password, setPassword] = useState()

    createUserWithEmailAndPassword(auth, email, password)
      .then((userCredential) => {
        // Signed in 
        const user = userCredential.user;
        // ...
      })
      .catch((error) => {
        const errorCode = error.code;
        const errorMessage = error.message;
        // ..
      });
```
### 6. Add login feature

Use signInWithEmailAndPassword.
```javascript
    // an example
    import { getAuth, signInWithEmailAndPassword } from "@firebase/auth";
    
    const Login = () => {
    
    const inputEmailRef = useRef();
    const inputPasswordRef = useRef();
    const auth = getAuth();

    const loginHandler = (event) => {
    event.preventDefault();
    const email = inputEmailRef.current.value;
    const password = inputPasswordRef.current.value;
    signInWithEmailAndPassword(auth, email, password)
    .then((userCredential) => {

    // Manage login

    })
    .catch((error) => {

     // Manage error

    });
    };
```
### 7. Add logout feature

Use signOut.
```javascript
    import { getAuth, signOut } from "firebase/auth";
    const auth = getAuth();

    const logoutHandler = () => {
    signOut(auth)
    .then(() => {

    // Manage sign out

    })

    .catch((error) => {

    // Manage error

    });
    };
```
Please visit [here](https://firebase.google.com/docs/auth/web/password-auth) for more detailed information.

Thank you for reading :)

The original article is [here](https://medium.com/@lada496/to-do-list-with-firebase-web-ver-9-75e264ec7eba)