Skip to content

Instantly share code, notes, and snippets.

@dominikkaegi
Last active March 12, 2020 00:42
Show Gist options
  • Select an option

  • Save dominikkaegi/275b4d5f9e9098b43c2ac78dcdc3d93e to your computer and use it in GitHub Desktop.

Select an option

Save dominikkaegi/275b4d5f9e9098b43c2ac78dcdc3d93e to your computer and use it in GitHub Desktop.

React Day 3

WIFI: Penguine House

Password: Penguin2019

Agenda

First Day

  • Introduction
  • JS Catch Up
  • Kahoot Quiz: https://kahoot.it/
  • React Project Setup
  • Creating React Elements
  • Creating React Components
  • Passing Props
  • Reusing Components

Second Day

  • Checkin
  • Kahoot Quiz: https://kahoot.it/
  • Handling Events
  • Conditional Rendering
  • Rendering Lists
  • Using State

Third-Day

  • Checkin
  • Importing / Exporting in JS
  • Firebase Setup
  • Promises
  • useEffect
  • Hooks
  • Todo App Interaction with Backend
    • Get Todos
    • Create Todo
    • Update Todos
    • Delete Todo

General Info

  1. Have a recent version of node installed or download it now from nodejs

    • (If you are on windows you probably also want to install windows bash)
  2. Join Whatsapp Group link: https://chat.whatsapp.com/HhEbt2Sb3ClJNfHFPttnn5

  3. Join Penguin Academy: https://tribe.penguin.academy/

  4. Create your solutions on CodeSandbox. You can log in with your Github account. https://codesandbox.io/

  5. Download VS Code Life Share

Let's Continue

git clone https://github.com/dominikkaegi/react-todo
git cd react-todo

npm install

npm run start

Adding Done Status

As a next step, we want to add a done status, so that we can indicate if a task is already completed.

Project Overview

  • What is Package.json
  • Importing and Exporting Files

Setting up Firebase

Creating Firebase Project

  1. Create an account on firebase.
  2. Go to your console firebase console
  3. Click on "Add project"
  4. Enter a name for your project: "todo-list-react"
  5. Disable Google Analytics
  6. Click on "Create Project"
  7. Wait until the project is created then press "continue"

Adding firebase to your application

  1. On the main page after creating the application, click on Database the </> sign to get started on the web.
  2. Register Your App by giving it a name, e.g. 'todo-list-react'
  3. Copy the firbaseConfig code.
  4. Within your react-project install firebase with npm install firebase
  5. Add a utils folder below your src folder
  6. Within the utils folder add a base.js file in which we will configure firebase

Your base.js should look something like this

import * as firebase from "firebase/app";
import "firebase/auth";
import "firebase/firestore";

const fireApp = firebase.initializeApp({
  apiKey: "your-credentials",
  authDomain: "your-credentials",
  databaseURL: "your-credentials",
  projectId: "your-credentials",
  storageBucket: "your-credentials",
  messagingSenderId: "your-credentials",
  appId: "your-credentials"
});

const db = firebase.firestore();
export { db };

export default fireApp;

Fallback credentials

const fireApp = firebase.initializeApp({
  apiKey: "AIzaSyCTFRvAtPrPiMUTP4Oi8gMion_jSK1gHfA",
  authDomain: "todo2-1bc55.firebaseapp.com",
  databaseURL: "https://todo2-1bc55.firebaseio.com",
  projectId: "todo2-1bc55",
  storageBucket: "todo2-1bc55.appspot.com",
  messagingSenderId: "903174892597",
  appId: "1:903174892597:web:208366efb28ce905d3957c"
});

Adding a database

  1. Within your application on firebase click on "Database"
  2. Click on Create Database at the top to create a Cloud Firestore
  3. Select "Start in test mode"
  4. Select the location (keep default)

Create a "todos" collection

  1. Click on 'Start collection'
  2. Add two fields task: string and isDone: boolean. Add some data to the string. Firebase will then create our first document in that collection.

Now we are all set up and done and can start using the firestore

Hooking up Todolist with Backend

Promises Excursion

const promise = new Promise((resolve, reject) => {
  let requestSuccessful = false
  setTimeout(() => {
    if(requestSuccessful) {
      resolve('data')
    } else {
      reject(new Error('Loading data failed'))
    }
  }, 1000)
})

promise.then(data => {
  console.log(data)
}).catch(err => {
  console.error(err)
})

Getting Todos from the Backend

  1. Create a function which retrieves all the existing todos form the backend
  2. Use the function within your component to load all the todos on the initial render

Create a todo

  1. Create a createTodo function which creates a todo
  2. Use the function within your component to create a todo and then display it to the user

Delete a todo

  1. Create a deleteTodo function which deletes a todo on the backend
  2. Use the function within your application to delete a todo on the backend and then update the frontend

Update a todo

  1. Create a function which switches the isDone Status of a todo on the backend
  2. Use the function within your application to change the isDone on the backend and then on the front end.

Additional Content:

Daily Challenges

  1. Build your own Calculator

State Challenges

1. First Time State

Create a counter which has an increase and a decrease button. When you click on one of the buttons the count should either increase or decrease.

See Example: https://dk0uh.csb.app/

2. Lifting State Exercise

Create a static and a shared counter component. Each component displays three counters which can be increased when clicking on a button. When clicking on a static counter only the count of that single static counter should be increased. On the other hand, when clicking on the increase button of a shared counter, the count of all shared counters should be increased.

See Example: https://w4zi2.csb.app/

import SharedCounter from "./SharedCounter";
import StaticCounter from "./StaticCounter";

export default function App() {
  return (
    <div className="App">
      <SharedCounter />
      <StaticCounter />
    </div>
  );
}

Firebase operation code

import { db } from "./base";

export const getAllTodos = () => {
  return db
    .collection("todos")
    .get()
    .then(snapshot => {
      const todos = snapshot.docs.map(item => {
        return {
          ...item.data(),
          id: item.id
        };
      });
      return todos;
    });
};

export const createTodo = ({ task, isDone = false }) => {
  return db
    .collection("todos")
    .add({
      task,
      isDone
    })
    .then(item => {
      return item.get().then(data => {
        let newTodo = {
          ...data.data(),
          id: data.id
        };
        return newTodo;
      });
    });
};

export const deleteTodo = id => {
  return db
    .collection("todos")
    .doc(id)
    .delete();
};

export const toggleIsDone = todo => {
  return db
    .collection("todos")
    .doc(todo.id)
    .update({ isDone: !todo.isDone });
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment