Share
Explore

Lab Coding Workbook: REACT and FireBase

This is the starter Workflow for your Project:
So let’s do good, well-formed NPM Application Development so we can submit the project with
npm -publish

In terms of the project: You will create a GITHUB Repository for all team members to do the push and pull to keep their local repositories in sync.
{On Tuesday we will demonstrate sync’ing with a GITHUB Repository from within VSC: All you are doing is git init in your Directory and using GIT CLI. So you must have a GIT client in your OS.}
In Capstone MAD 5274: We will be using TRELLO. Let’s get started with TRELLO as the way to do project Management for our Project.
To start the Project: Decide on your Team.
Appoint one team member to be the Libarian/Document Manager for the Team.
Team Communication Officer will create a TRELLO Board: Make all your TEAM, and peter@petersigurdson.net, to be editors of that Board.
Make a text file: named as teamname.txt:
Into this file: Put team members’ names and student IDs
Put your LINK to your TRELLO Board.


Let’s make a react app which presents a form and stores the data into Firebase — Which is a json schema database.
Have Node.js installed to follow along with this tutorial.

These instructions will use Firestore Database and not Firebase Realtime database.


STEP 1: Set Up a New React Project
image.png
Firstly, you need to create a new React project. Navigate to your preferred directory and run the following commands:
npx create-react-app form-to-firebase
cd form-to-firebase
npm start
The npm start command runs your application. Visit http://localhost:3000 to view it. If you see the React logo with a message saying "Edit src/App.js and save to reload", then your setup is successful.
STEP 2: Setting Up Firebase
a. Open the in your browser and sign in with gmail credentials. ​
image.png
b. Click on "Add Project", fill in the necessary details, and agree to the terms, then click "Create Project".
c. After creation, click on the project, in the sidebar select "Firestore Database", then "Create Database". Start the database in "test mode".
d. Click on the "</>" icon to add Firebase to your web app. ​
image.png
Copy the configuration settings object, we will use them shortly.
image.png
STEP 3: Install Firebase SDK
Navigate to your project directory and install Firebase SDK by running this command:
npm install firebase
STEP 4: Setup Firebase configuration
a. In your src directory, create a new file named firebase.js.
b. Paste your previously copied Firebase configuration into the firebase.js file:
import firebase from 'firebase/app'
import 'firebase/firestore'

var firebaseConfig = {
apiKey: "[API_KEY]",
authDomain: "[AUTH_DOMAIN]",
projectId: "[PROJECT_ID]",
storageBucket: "[STORAGE_BUCKET]",
messagingSenderId: "[SENDER_ID]",
appId: "[APP_ID]"
};

firebase.initializeApp(firebaseConfig);

export const db = firebase.firestore()
Open in: CodeSandBox
Please replace [...] with the actual values gotten from your Firebase project.
STEP 5: Create a Form
Let's make a simple form to collect user names in the App.js file:
import React, { useState } from 'react';
import { db } from './firebase'

function App() {
const [name, setName] = useState('');

const onSubmit = (e) => {
e.preventDefault();

db.collection('users').add({
name
// more fields can be added here
}).then(() => {
setName('');
});
};

return (
<form onSubmit={onSubmit}>
<h1>Simple Form</h1>

<label>Name</label>
<input type="text" value={name} onChange={e => setName(e.currentTarget.value)}/>

<button type="submit">Submit</button>
</form>
);
}

export default App;
After submission, the form should reset and the data should be stored in Firebase.
You can verify submission on the Firebase console. Make sure you switch from "Cloud Firestore" to "Data" on the Firebase console to view your data.
This is a basic setup.
Depending on the complexity of your project, you might have to handle errors and validations for your form.
Also, always remember to secure your Firebase console before deploying the application, to prevent unauthorized access and modifications.

megaphone
How to change your thinking when you are using JSON rather than SQL:

Adapting mobile React applications to integrate with JSON schema in a way that fully embraces the NoSQL paradigm involves several key developer evolutions.

These changes not only require technical adjustments but also a shift in mindset towards how data is structured, accessed, and manipulated.

Here are five key evolutions for developers to consider:


Embracing Schema Flexibility: NoSQL databases, especially those using JSON, typically don’t enforce a fixed schema like traditional SQL databases.
Developers should evolve to design data structures that are adaptable and evolve over time.
This means creating React components and data handling logic that can dynamically adjust to varying data structures.
This flexibility allows for faster iterations and adaptations to changing application requirements.

Mastering Denormalization: Unlike SQL databases that normalize data across multiple tables, NoSQL often uses denormalization, where related data is stored together.
Developers should learn to effectively denormalize data for optimal performance in NoSQL databases.
This involves understanding how to aggregate data in a way that aligns with the application’s access patterns, reducing the need for complex joins and enhancing performance.

Leveraging JSON for Data Exchange: JSON is a native format for many NoSQL databases and is also easily consumed by React applications. Developers should become proficient in using JSON for both server-client and database communication. This involves understanding the serialization and deserialization of JSON data, as well as handling dynamically structured JSON in a way that the React application can efficiently process.

Optimizing for Offline-First Design: Mobile applications often need to function effectively in intermittent connectivity scenarios. Developers should evolve to design React applications with an offline-first approach, where data synchronization and conflict resolution are key.
This requires effective use of local storage and caching strategies, and understanding how to synchronize local changes with the backend NoSQL database once connectivity is restored.

Understanding Eventual Consistency: NoSQL databases often follow the principle of eventual consistency, as opposed to the immediate consistency of primary key-driven and ACID SQL databases.
This requires a shift in how developers handle data integrity and synchronization in React applications.
Understanding how to manage and inform users about data synchronization states, and handling potential conflicts in data due to this eventual consistency model, becomes crucial.
By focusing on these areas, developers can more effectively align their React mobile applications with the principles and advantages of NoSQL databases, leveraging the power of JSON schema for more flexible, scalable, and efficient application development.

React Lab Coding Workbook on making a react app which presents a form and stores the data into firebase which is a json schema database

React Lab Coding Workbook: Building a React App with Firebase Integration

Introduction

In this lab, you'll learn how to create a basic React application that includes a form.
This form will send data to Firebase, a popular NoSQL database that uses JSON schema.
The focus will be on simplicity and clarity to ensure you understand each step.

Prerequisites

Basic understanding of HTML, CSS, and JavaScript
Node.js installed on your computer
A text editor (like Visual Studio Code)
A Firebase account (it's free!)

Setting Up Your Project

Create a New React App:
Open your terminal or command prompt.
Run npx create-react-app firebase-react-form.
Navigate into your new project with cd firebase-react-form.
Install Firebase:
Inside your project directory, run npm install firebase.

Setting Up Firebase

Create a Firebase Project:
Go to the Firebase Console ().
Click on "Add Project" and follow the steps.
Add a Web App to Your Firebase Project:
Click on 'Web' icon to add a web app.
Register your app and follow the setup instructions.
You'll get a configuration object – keep it handy for later.
Initialize Firebase in Your React App:
Create a file named firebase.js in your src folder.
Import Firebase and initialize it with your config object:
import firebase from 'firebase/app'; import 'firebase/database';
const firebaseConfig = { // Your config object goes here };
firebase.initializeApp(firebaseConfig);
export default firebase;

Building the React Form

Create a Form Component:
In your src folder, create a new file named Form.js.
Start by importing React and setting up a basic form structure:
import React, { useState } from 'react';
function Form() { const [formData, setFormData] = useState({ name: '', email: '' });
const handleChange = (e) => { setFormData({...formData, [e.target.name]: e.target.value }); };
const handleSubmit = (e) => { e.preventDefault(); // We will add Firebase submission logic here };
return ( <form onSubmit={handleSubmit}> <input type="text" name="name" placeholder="Name" value={formData.name} onChange={handleChange} /> <input type="email" name="email" placeholder="Email" value={formData.email} onChange={handleChange} /> <button type="submit">Submit</button> </form> ); }
export default Form;

Add the Form Component to App.js:
Open App.js.
Import and include your Form component:
import React from 'react'; import Form from './Form';
function App() { return ( <div className="App"> <h1>React Firebase Form</h1> <Form /> </div> ); }
export default App;

Integrating Firebase for Data Storage

Storing Form Data in Firebase:
Modify the handleSubmit function in your Form.js:
import firebase from './firebase';
// Inside your Form component const handleSubmit = (e) => { e.preventDefault(); firebase.database().ref('entries').push(formData) .then(() => { alert('Data submitted!'); setFormData({ name: '', email: '' }); // Clear form }) .catch((error) => { alert('Error: ', error.message); }); };

Conclusion

Congratulations! You've just built a simple React application that submits data to Firebase. This lab provided a basic introduction to integrating Firebase with React. As you progress, you'll learn more about handling real-time data, user authentication, and other advanced features of Firebase.
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.