0% found this document useful (0 votes)
20 views8 pages

Unit4 - Ques

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)
20 views8 pages

Unit4 - Ques

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/ 8

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.

To fetch data from a public API in React, you can use the Fetch API along with React’s
useEffect and useState hooks.

● Steps:

1. Use useState to store fetched data.


2. Use useEffect to call the API when the component loads.
3. Use Fetch API to get data and update the state.
● Example:

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

const App = () => {


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

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

return (
<div>
<h1>Users</h1>
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
</div>
);
};

export default App;

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?

● useEffect runs side effects like data fetching in React components.


● By passing an empty dependency array [], it ensures that the function inside runs only
once when the component is first rendered (on mount).
● This prevents multiple unnecessary API calls.

Example:

useEffect(() => {
fetchData();
}, []); // Empty array = run only on mount

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?

● Scenario: If the API server is down or the URL is incorrect, you need to display an error
message to users.
● Error Handling: Use a try-catch block to catch errors and update a separate error
state.

Example:

const [error, setError] = useState(null);

const fetchUsers = async () => {


try {
const response = await fetch('https://example.com/api');
if (!response.ok) throw new Error('API Error');
const data = await response.json();
setUsers(data);
} catch (error) {
setError(error.message);
}
};

Using Firebase with React

1. What are the steps involved in setting up Firebase in a React project?

1. Create a Firebase Project: Go to Firebase console and create a project.


2. Install Firebase SDK: Use npm install firebase in your project.
3. Initialize Firebase:
○ Create a firebase.js file.

Add your Firebase config and initialize Firestore:


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);
export const db = firebase.firestore();

2. How do you perform CRUD operations using Firebase Firestore in a React application?

Create: Add a new document.

const createUser = async () => {


await db.collection('users').add({ name: 'John', age: 25 });
};

1.

Read: Get documents.

const getUsers = async () => {


const snapshot = await db.collection('users').get();
const users = snapshot.docs.map(doc => doc.data());
console.log(users);
};

2.

Update: Update a document.

const updateUser = async (id) => {


await db.collection('users').doc(id).update({ age: 26 });
};

3.

Delete: Delete a document.

const deleteUser = async (id) => {


await db.collection('users').doc(id).delete();
};

4.

3. Explain the benefits of using Firebase Authentication in a React application.

● Simplified Authentication: Provides built-in support for email/password, Google,


Facebook, etc.
● Secure: Firebase handles token management and security checks.
● Real-Time Sync: Works well with Firestore for real-time user-based data.
● Cross-Platform: Easily integrates with web, iOS, and Android apps.

Cloud Databases

1. Compare and contrast SQL and NoSQL databases. When would you choose to use
each type of database in a React application?

Feature SQL NoSQL

Structure Relational (tables) Non-relational (JSON, etc.)


Scalability Vertical (add Horizontal (add servers)
resources)

Data Type Structured Semi/unstructured

Examples MySQL, PostgreSQL MongoDB, Firebase Firestore

● Use SQL: For structured data like inventory or banking apps.


● Use NoSQL: For flexible, scalable data like social media or IoT.

2. Describe how to connect a React app to a MongoDB cloud database.

Install MongoDB driver:

npm install mongodb

1.

Connect:

import { MongoClient } from 'mongodb';

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


const client = new MongoClient(uri);

async function connectDB() {


await client.connect();
const db = client.db('myDatabase');
const users = await db.collection('users').find().toArray();
console.log(users);
}
connectDB();

2.

3. Explain the concept of data consistency in cloud databases. How do SQL and NoSQL
databases handle data consistency differently?

● Data Consistency: Ensures that data remains accurate across database transactions.
● SQL: Strong consistency (data always consistent due to ACID rules).
● NoSQL: Eventual consistency (data updates propagate over time for better scalability).
General Questions

1. How do you decide which cloud database to use for a React application?

Factors to consider:

● Data Structure: Use SQL for structured data, NoSQL for flexibility.
● Scalability: NoSQL for scaling needs (e.g., large traffic).
● Complex Queries: SQL is better for complex relationships.
● Real-Time Needs: NoSQL like Firebase for real-time updates.

2. Explain the importance of data security when using cloud databases in a React
application.

● Protects sensitive user data.


● Prevents unauthorized access and data breaches.
● How:
○ Use SSL/TLS for secure connections.
○ Authenticate users (e.g., Firebase Authentication).
○ Restrict access with roles and permissions.

3. Describe a scenario where you might need to use both SQL and NoSQL databases in a
single React application.

● Scenario: E-commerce app.


○ SQL: Store structured transactional data like orders and payments.
○ NoSQL: Manage flexible data like product catalogs or user reviews.

Integration: Use APIs to combine data from both databases into the React app.

___________________________________________________________

1. Load Balancer: Distributes incoming traffic across multiple instances or servers to


improve application availability and fault tolerance.

2. Instances: Virtual servers in the cloud used to run applications (e.g., EC2 in AWS).
3. Route Table: Defines rules for routing traffic within a Virtual Private Cloud (VPC).

4. Internet Gateway: A VPC component that allows communication between your VPC
resources and the internet.

5. Subnet: A segment of a VPC where you can group resources based on routing and
security needs.

6. Use of npm start: Runs the startup script defined in package.json to start a
development server for a React app.

7. Use of package.json: Contains metadata for the project, including dependencies and
scripts.

8. Use of Component in React: Encapsulates reusable UI elements with their behavior


and state.

9. Difference Between Class and Function: Class components have lifecycle methods
and state; functional components are simpler and can use hooks for state and effects.

10. Amplify in AWS: A service for building, deploying, and hosting web and mobile
applications with backend support.

11. Use of Role in AWS: Assigns permissions to AWS resources to interact with other
services securely.

12. Use of AWS Bucket: Stores data, such as files or media, in Amazon S3.

13. Firebase: A backend-as-a-service providing tools like authentication, database, and


hosting, often used with React for rapid development.

14. Use of Arrow Function in React: Simplifies syntax and maintains the correct this
context in components.

15. Use of Security Group: Acts as a virtual firewall to control traffic to and from AWS
resources.

16. Use of VPC: Enables the creation of isolated networks for your AWS resources.

17. What is VM: A virtualized computing environment that mimics a physical computer.

18. What is Target Group: A collection of resources (e.g., EC2 instances) that receive
traffic routed by a load balancer.

You might also like