Developing Web App using React Cosmos DB - Create Project
Developing a Web App Using React and Cosmos DB
In this tutorial, we will walk through the process of developing a web application using React as the front-end framework and Azure Cosmos DB for the back-end database. This tutorial is inspired by the YouTube video titled "Developing Web App using React Cosmos DB - Create Project 2 minutes, 12 seconds." We will highlight the key steps and concepts to help you create your own web app seamlessly.
Prerequisites
Before we dive into the development process, ensure you have the following prerequisites:
- Node.js and npm: Make sure you have Node.js installed on your machine. You can download it from nodejs.org.
- Azure Account: Sign up for an Azure account if you don’t have one. You can create a free account at azure.com.
- Basic knowledge of React: Familiarity with React will help you understand the concepts better.
Step 1: Setting Up the React Application
To start, we will set up a new React application using Create React App. Open your terminal and run the following command:
npx create-react-app my-web-app
This command creates a new directory called my-web-app with a boilerplate React application. Once the installation is complete, navigate into your project folder:
cd my-web-app
Step 2: Installing Dependencies
Next, we will need to install a few additional dependencies to connect our React app to Azure Cosmos DB. For this, we will use the @azure/cosmos package. Install it using npm:
npm install @azure/cosmos
Step 3: Setting Up Azure Cosmos DB
Create a Cosmos DB Account:
- Log in to your Azure portal.
- Click on "Create a resource" and search for "Azure Cosmos DB".
- Choose your preferred API (SQL API is commonly used) and fill in the required information.
- Click "Review + Create" and then "Create".
Create a Database and Container:
- Once your Cosmos DB account is created, navigate to it.
- Under the "Data Explorer" section, create a new database (e.g.,
MyDatabase). - Inside the database, create a new container (e.g.,
MyContainer) and set a partition key (for example,/id).
Get Connection String:
- In the settings of your Cosmos DB account, locate the connection string. You will need this to connect your React application to the database.
Step 4: Connecting React to Cosmos DB
Now that we have set up the backend, we can connect our React application to Azure Cosmos DB. Create a new file called cosmosDb.js in the src directory of your React project.
Sample Code for Connecting to Cosmos DB
// src/cosmosDb.js
import { CosmosClient } from '@azure/cosmos';
// Replace with your Cosmos DB connection string
const endpoint = 'YOUR_COSMOS_DB_ENDPOINT';
const key = 'YOUR_COSMOS_DB_KEY';
const client = new CosmosClient({ endpoint, key });
export const getItems = async () => {
const { resources: items } = await client.database('MyDatabase').container('MyContainer').items.readAll().fetchAll();
return items;
};
export const addItem = async (item) => {
const { resource: createdItem } = await client.database('MyDatabase').container('MyContainer').items.create(item);
return createdItem;
};
Explanation
- We import the
CosmosClientfrom the@azure/cosmospackage. - We initialize the client using the endpoint and key from your Cosmos DB account.
- We define two functions:
getItemsto fetch items from the database andaddItemto add new items.
Step 5: Using Cosmos DB in Your React Component
Let’s update our App.js file to use the functions we created to interact with Azure Cosmos DB.
// src/App.js
import React, { useEffect, useState } from 'react';
import { getItems, addItem } from './cosmosDb';
function App() {
const [items, setItems] = useState([]);
useEffect(() => {
const fetchData = async () => {
const data = await getItems();
setItems(data);
};
fetchData();
}, []);
const handleAddItem = async () => {
const newItem = { id: '1', name: 'New Item' }; // Example item
const addedItem = await addItem(newItem);
setItems((prevItems) => [...prevItems, addedItem]);
};
return (
<div>
<h1>My Web App</h1>
<button onClick={handleAddItem}>Add Item</button>
<ul>
{items.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
</div>
);
}
export default App;
Explanation
- We import
useEffectanduseStatefrom React to manage state and lifecycle. - In the
useEffecthook, we fetch items from the database when the component mounts. - The
handleAddItemfunction demonstrates how to add a new item to the database.
Step 6: Running Your Application
With everything set up, you can run your application. In your terminal, execute:
npm start
This command starts your React application, and you should see the UI in your browser. You can now add items and see them listed.
Conclusion
Congratulations! You have successfully developed a web application using React and Azure Cosmos DB. This tutorial covered the necessary steps to set up your development environment, connect to Cosmos DB, and interact with your database from a React app.
Feel free to expand on this foundation by adding more features, such as editing and deleting items, or implementing user authentication. Happy coding!
Connect with SkillBakery Studios
Explore more tutorials, tools, and resources:
Posted by SkillBakery Studios


No comments:
Post a Comment