0% found this document useful (0 votes)
28 views10 pages

Unit IV Notes

Uploaded by

ramyashreeg2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views10 pages

Unit IV Notes

Uploaded by

ramyashreeg2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Connecting React with Cloud APIs: Fetching Data from a Public API and Displaying it in

React

Overview

React applications often need to fetch data from external APIs to provide dynamic and
up-to-date content. This section will guide you through the process of fetching data from a public
API and displaying it in a React application.

Steps to Fetch Data from a Public API

1. Create a React Application


- Use `create-react-app` to scaffold a new React project:

npx create-react-app my-react-app


cd my-react-app

2. Select a Public API


- Choose a public API that provides the data you need. For example, JSONPlaceholder offers
various endpoints for testing purposes:

https://jsonplaceholder.typicode.com/users

3. Use Fetch API to Retrieve Data


- Open `src/App.js` and import `useState` and `useEffect` hooks:

import React, { useState, useEffect } from 'react';

- Create a state to hold the fetched data:

const [users, setUsers] = useState([]);

- Define a function to fetch data using the Fetch API:

const fetchUserData = async () => {


try {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
const data = await response.json();
setUsers(data);
} catch (error) {
console.error('Error fetching data:', error.message);
}
};

- Use `useEffect` to call `fetchUserData` when the component mounts:

useEffect(() => {
fetchUserData();
}, []);

4. Display the Fetched Data


- Render the fetched data in your component:

return (
<div>
<h1>Users</h1>
<ul>
{users.map((user) => (
<li key={user.id}>
<strong>Username:</strong> {user.username}, <strong>Full Name:</strong>
{user.name}, <strong>Email:</strong> {user.email}
</li>
))}
</ul>
</div>
);

Example Code

import React, { useState, useEffect } from 'react';

const App = () => {


const [users, setUsers] = useState([]);

const fetchUserData = async () => {


try {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
const data = await response.json();
setUsers(data);
} catch (error) {
console.error('Error fetching data:', error.message);
}
};

useEffect(() => {
fetchUserData();
}, []);

return (
<div>
<h1>Users</h1>
<ul>
{users.map((user) => (
<li key={user.id}>
<strong>Username:</strong> {user.username}, <strong>Full Name:</strong>
{user.name}, <strong>Email:</strong> {user.email}
</li>
))}
</ul>
</div>
);
};

export default App;

Using Firebase with React: Setting Up Firebase in a React Project, CRUD Operations
Using Firebase Firestore

Overview

Firebase is a popular backend-as-a-service (BaaS) that provides various tools for building web
and mobile applications. This section will cover setting up Firebase in a React project and
performing CRUD operations using Firebase Firestore.

Setting Up Firebase in a React Project

1. Create a Firebase Project


- Go to the Firebase console and create a new project.

2. Install Firebase SDK


- Install the Firebase SDK in your React project:

npm install firebase


3. Initialize Firebase
- Create a new file `firebase.js` and initialize Firebase:

import firebase from 'firebase/app';


import 'firebase/firestore';

const firebaseConfig = {
apiKey: 'YOUR_API_KEY',
authDomain: 'YOUR_AUTH_DOMAIN',
projectId: 'YOUR_PROJECT_ID',
};

firebase.initializeApp(firebaseConfig);

const db = firebase.firestore();

export default db;

CRUD Operations Using Firebase Firestore

1. Create Data
- Use `addDoc` to create a new document in Firestore:

import db from './firebase';

const createUser = async (user) => {


try {
const docRef = await addDoc(collection(db, 'users'), user);
console.log('User created with ID:', docRef.id);
} catch (error) {
console.error('Error creating user:', error.message);
}
};

2. Read Data
- Use `getDocs` to read documents from Firestore:

import db from './firebase';

const getUsers = async () => {


try {
const querySnapshot = await getDocs(collection(db, 'users'));
const users = querySnapshot.docs.map((doc) => doc.data());
console.log('Users:', users);
} catch (error) {
console.error('Error reading users:', error.message);
}
};

3. Update Data
- Use `updateDoc` to update a document in Firestore:

import db from './firebase';

const updateUser = async (userId, user) => {


try {
const docRef = doc(db, 'users', userId);
await updateDoc(docRef, user);
console.log('User updated with ID:', userId);
} catch (error) {
console.error('Error updating user:', error.message);
}
};

4. Delete Data
- Use `deleteDoc` to delete a document from Firestore:

import db from './firebase';

const deleteUser = async (userId) => {


try {
const docRef = doc(db, 'users', userId);
await deleteDoc(docRef);
console.log('User deleted with ID:', userId);
} catch (error) {
console.error('Error deleting user:', error.message);
}
};

Example Code

import React, { useState, useEffect } from 'react';


import db from './firebase';
const App = () => {
const [users, setUsers] = useState([]);

const createUser = async (user) => {


try {
const docRef = await addDoc(collection(db, 'users'), user);
console.log('User created with ID:', docRef.id);
} catch (error) {
console.error('Error creating user:', error.message);
}
};

const getUsers = async () => {


try {
const querySnapshot = await getDocs(collection(db, 'users'));
const users = querySnapshot.docs.map((doc) => doc.data());
setUsers(users);
} catch (error) {
console.error('Error reading users:', error.message);
}
};

const updateUser =

Cloud Databases: Types of Cloud Databases (SQL vs NoSQL), Connecting a React App to
a Cloud Database

Overview

Cloud databases offer a flexible and scalable way to manage data in web applications. This
section will cover the types of cloud databases, focusing on SQL and NoSQL databases, and
provide guidance on connecting a React app to a cloud database.

Types of Cloud Databases

1. SQL Cloud Databases


- Relational Databases: SQL databases are relational databases that store data in tables with
fixed rows and columns. They are ideal for structured data and applications that require
complex queries and data consistency.
- Examples: MySQL, PostgreSQL, Oracle, MS-SQL Server.
2. NoSQL Cloud Databases
- Non-Relational Databases: NoSQL databases are non-relational databases that store data in
various formats such as documents, key-value pairs, graphs, and wide-column stores. They are
suitable for unstructured or semi-structured data and applications that require high scalability
and flexibility.
- Examples: MongoDB, Cassandra, HBase, Redis, Neo4j.

Connecting a React App to a Cloud Database

1. Choosing a Cloud Database


- SQL: Use SQL databases for applications that require structured data and complex queries.
Examples include accounting systems, sales databases, and transactional systems.
- NoSQL: Use NoSQL databases for applications that require high scalability, flexibility, and
handling of unstructured data. Examples include social networks, real-time analytics, and IoT
applications.

2. Connecting to a Cloud Database


- SQL: Use SQL drivers or libraries to connect to SQL cloud databases. For example, use
`mysql` package for MySQL or `pg` package for PostgreSQL.
- NoSQL: Use specific drivers or libraries for each NoSQL database. For example, use
`mongodb` package for MongoDB or `cassandra-driver` package for Cassandra.

3. Example: Connecting a React App to a MongoDB Cloud Database


- Install MongoDB Driver: Install the MongoDB driver using npm:

npm install mongodb

- Connect to MongoDB: Import the MongoDB driver and connect to your MongoDB cloud
database:

import { MongoClient } from 'mongodb';

const uri = 'mongodb+srv://username:[email protected]/';


const client = new MongoClient(uri);

async function connectToMongoDB() {


try {
await client.connect();
console.log('Connected to MongoDB');
} catch (error) {
console.error('Error connecting to MongoDB:', error.message);
}
}
connectToMongoDB();

- Fetch Data: Use the MongoDB client to fetch data from your database:

async function fetchUserData() {


try {
const db = client.db();
const usersCollection = db.collection('users');
const users = await usersCollection.find().toArray();
console.log('Users:', users);
} catch (error) {
console.error('Error fetching users:', error.message);
}
}

fetchUserData();

Example Code

import React, { useState, useEffect } from 'react';


import { MongoClient } from 'mongodb';

const uri = 'mongodb+srv://username:[email protected]/';


const client = new MongoClient(uri);

const App = () => {


const [users, setUsers] = useState([]);

async function connectToMongoDB() {


try {
await client.connect();
console.log('Connected to MongoDB');
} catch (error) {
console.error('Error connecting to MongoDB:', error.message);
}
}

async function fetchUserData() {


try {
const db = client.db();
const usersCollection = db.collection('users');
const users = await usersCollection.find().toArray();
setUsers(users);
} catch (error) {
console.error('Error fetching users:', error.message);
}
}

useEffect(() => {
connectToMongoDB();
fetchUserData();
}, []);

return (
<div>
<h1>Users</h1>
<ul>
{users.map((user) => (
<li key={user._id}>
<strong>Username:</strong> {user.username}, <strong>Full Name:</strong>
{user.fullName}, <strong>Email:</strong> {user.email}
</li>
))}
</ul>
</div>
);
};

export default App;

Summary
- SQL databases are ideal for structured data and applications that require complex queries and
data consistency.
- NoSQL databases are suitable for unstructured or semi-structured data and applications that
require high scalability and flexibility.
- Connecting a React app to a cloud database involves choosing the appropriate database type
and using specific drivers or libraries to connect and interact with the database.
Sample Questions from Unit-IV :-

Connecting React with Cloud APIs

1. How do you fetch data from a public API in a React application? Provide an example using
the Fetch API.
2. Explain the role of `useEffect` in fetching data from a public API in React. How does it ensure
that the API is called only once when the component mounts?
3. Describe a scenario where you might need to handle errors when fetching data from a public
API in React. How would you implement error handling in such a case?

Using Firebase with React

1. What are the steps involved in setting up Firebase in a React project? Explain how to initialize
Firebase and connect to Firestore.
2. How do you perform CRUD operations using Firebase Firestore in a React application?
Provide examples for creating, reading, updating, and deleting documents.
3. Explain the benefits of using Firebase Authentication in a React application. How does it
simplify user authentication and authorization?

Cloud Databases

1. Compare and contrast SQL and NoSQL databases. When would you choose to use each
type of database in a React application?
2. Describe how to connect a React app to a MongoDB cloud database. What are the
necessary steps and libraries required for this connection?
3. Explain the concept of data consistency in cloud databases. How do SQL and NoSQL
databases handle data consistency differently?

General Questions

1. How do you decide which cloud database to use for a React application? What factors should
you consider when making this decision?
2. Explain the importance of data security when using cloud databases in a React application.
How can you ensure that your data is secure?
3. Describe a scenario where you might need to use both SQL and NoSQL databases in a
single React application. How would you integrate these databases?

You might also like