DEV Community

Cover image for React TODO with Firebase for database and deploy
Mallikarjun H T
Mallikarjun H T

Posted on • Updated on

React TODO with Firebase for database and deploy

Well we all know a task manager app and wonder how to do one don't worry I got it covered for you.

I will share each and every code snippet and explain how to host and use the app.

Lets jump right into the code without wasting time.

I am using Material-Ui for styling the components. any frame work is fine as long as you follow the syntax.

My Input and Button Component

i have used ES6 Arrow function and React hooks most of the places.

<FormControl>
    <InputLabel htmlFor="my-input">Add Task</InputLabel>
    <Input value={input} onChange={(event) => 
        setInput(event.target.value)} />
    <Button disabled={!input} type="submit" 
        variant="contained" color="primary" type="submit" 
        onClick={addTask} >Add Task
    </Button>
</FormControl>
Enter fullscreen mode Exit fullscreen mode

To list the tasks i have used simple JSX syntax and passing props to Todo component and i will explain in a bit.

{tasks.map(task => (<Todo task={task} />))}
Enter fullscreen mode Exit fullscreen mode

i will be using Firebase to host and use Database for this project. The perpose here is to have a hosted application so i can use for my personal use.

here is a snippet for retriving data and set in state to display.

useEffect(()=>{
db.collection('todos')
  .orderBy('timestamp','desc')
  .onSnapshot(snapshot =>
      setTasks(snapshot.docs.map(doc => (
       { id: doc.id, title : doc.data().title , status : 
          doc.data().status })))
    )} ,[]);
Enter fullscreen mode Exit fullscreen mode

request for collection with name todos and map through each document and destructure it to save in state this allows us to easiley manuplte the data.

Adding new task

  const addTask = (event) => {
        event.preventDefault();
        db.collection('todos').add({
            title: input,
            status: false,
            timestamp: 
              firebase.firestore.FieldValue.serverTimestamp()
        })//add data to collection and i am using timestamp
        setInput(''); /*clears input field after adding new task try removing and you will find that the data is not cleared in input field*/
    }       
Enter fullscreen mode Exit fullscreen mode

Time to intriduce edit, delete and check the task operations

<div>
   <List component="nav" aria-label="main mailbox folders">
        <ListItem button>
        <Checkbox checked={props.task.status} onClick={event 
            => {db.collection('todos').doc(props.task.id)
               .update({status : !props.task.status})}}
        />
        {!edit ? 
            (<TextField id="standard-basic" 
             value={props.task.title} disabled />
            ) : 
            (<>
             <TextField id="standard-basic" 
               value={task.title} 
               onChange={event => 
               setTask({title: event.target.value, 
               id: props.task.id, 
               status: props.task.status})}
             />
            <Button  type="submit" 
             variant="contained" 
             color="primary" 
             type="submit"
             onClick={event =>stateChange(event)} >
             Submit
            </Button>
        </>
      )}
  </ListItem>
     {edit ?'': 
        <Button 
          onClick={(event) => setEdit(!edit)}>
        Edit
        </Button>}
      <ListItemSecondaryAction>
           <IconButton edge="end" aria-label="delete">
           <Button 
               onClick={event => {db.collection('todos')
               .doc(props.task.id).delete()}}>
           <DeleteIcon />
           </Button>
           </IconButton>
       </ListItemSecondaryAction>
  </List>
</div>
Enter fullscreen mode Exit fullscreen mode

State change and Edit operation

const stateChange = (event) =>{       
     db.collection('todos')
     .doc(props.task.id).update({title : task.title});
     setEdit(false);
 }
Enter fullscreen mode Exit fullscreen mode

wondering how why i use db every where!!!...

well its a firebase app config lets see how to inetilize firebase

import firebase from "firebase";
const firebaseapp = firebase.initializeApp(${{FIREBASE_CONFIG}});

const db = firebaseapp.firestore();

export  default db;
Enter fullscreen mode Exit fullscreen mode

For security reasion i have not included firebase secret and token dont worrey i will gide you on how to get the key and how to use this app.

lets dive into Build

colone this project and follow the steps along.
Github repo
This project was bootstrapped with Create React App.

Available Scripts

In the project directory, you can run:

npm start

Runs the app in the development mode.

Open http://localhost:3000 to view it in the browser.

The page will reload if you make edits.

You will also see any lint errors in the console.

npm run build

Builds the app for production to the build folder.

It correctly bundles React in production mode and optimizes the build for the best performance.

The build is minified and the filenames include the hashes.

Your app is ready to be deployed!

See the section about deployment for more information.

npm run build fails to minify

This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify

Firebase SetUp and Deploy

install firebase tools cli to continue

step 1:

npm install -g firebase-tools


step 2:

Login to firebase locally
firebase login

then chose the account you will be using to host and add firestore to.


step 3:

go to firebase console
* go to console
* Add project
* onece project is set
* chose firestore and make initial setup
* remember chose datbase in testmode for biginers once app is set you can always lock the database.
* copy the config and add in config.js file of the project


### step 4:
initilise the firebase in app
firebase init

  • use spacebar to select choose Hosting
  • choose build folder remember this is the folder that you will be using while deplying ! dont put in public as it already contain index.html file
  • choose single page application
  • if needed choose CI/CD for my case i have not ---

step 5:

build the project to install dependency before deploying
npm run build this is normail npm command but this time we will be doing on the build folder we created
!NOTE this will create a mimina folder to serve app faster refer React docks for more
---

Step 6:

finally we will be deploying our App
firebase deploy
and you will get a public URL use that to view your App

Happy Learning ๐Ÿ“š

Top comments (0)