Developing Web App using React Cosmos DB - Connect to CosmosDB
Developing a Web App using React and Cosmos DB: A Step-by-Step Guide
In today’s digital landscape, building robust web applications requires a combination of powerful frontend frameworks and scalable backend databases. This blog post will guide you through developing a web application using React as the frontend framework and Azure Cosmos DB as the backend database. We will focus on how to connect your React app to Cosmos DB, following the insights from the YouTube video titled "Developing Web App using React Cosmos DB - Connect to CosmosDB."
What is React?
React is a popular JavaScript library for building user interfaces, especially for single-page applications. It allows developers to create reusable UI components, making the development process more efficient and organized.
What is Azure Cosmos DB?
Azure Cosmos DB is a globally distributed, multi-model database service designed for high availability and low latency. It supports multiple data models, including document, key-value, graph, and column-family data, making it a versatile choice for modern applications.
Prerequisites
Before we start, ensure you have the following:
- Node.js and npm installed on your machine.
- An Azure account to create and manage your Cosmos DB instance.
- Basic understanding of React and JavaScript.
Step 1: Setting Up Your Cosmos DB
- Log in to your Azure account and navigate to the Azure portal.
- Click on Create a Resource and select Databases > Azure Cosmos DB.
- Choose the API you wish to use (for this tutorial, we will use the SQL API).
- Fill in the required fields like Subscription, Resource Group, Account Name, and Location.
- Click Review + Create and then Create to set up your Cosmos DB instance.
- Once created, navigate to the Keys section in your Cosmos DB account to retrieve your URI and Primary Key. You will need these to connect your React app to Cosmos DB.
Step 2: Setting Up Your React Application
Open a terminal and create a new React application using Create React App:
npx create-react-app my-cosmos-appNavigate to your new app directory:
cd my-cosmos-appInstall the necessary packages for making HTTP requests. We will use Axios for this purpose:
npm install axios
Step 3: Building the Connection to Cosmos DB
We will create a simple backend using Express.js to securely connect to Cosmos DB. This backend will handle requests from our React frontend.
Create a new directory for your server and navigate into it:
mkdir server cd serverInitialize a new Node.js project:
npm init -yInstall the required dependencies:
npm install express @azure/cosmos dotenv corsCreate a
.envfile in the server directory to store your Cosmos DB credentials:COSMOS_URI=your_cosmos_db_uri COSMOS_KEY=your_cosmos_db_primary_keyCreate a server file (e.g.,
server.js) and set up the Express server:const express = require('express'); const { CosmosClient } = require('@azure/cosmos'); const cors = require('cors'); require('dotenv').config(); const app = express(); app.use(cors()); app.use(express.json()); const client = new CosmosClient({ endpoint: process.env.COSMOS_URI, key: process.env.COSMOS_KEY }); const databaseId = 'YourDatabaseId'; const containerId = 'YourContainerId'; app.get('/api/items', async (req, res) => { const querySpec = { query: 'SELECT * from c' }; const { resources: items } = await client.database(databaseId).container(containerId).items.query(querySpec).fetchAll(); res.status(200).send(items); }); const PORT = process.env.PORT || 5000; app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); });Start your server:
node server.js
Step 4: Connecting React App to the Backend
Now, we will modify our React app to fetch data from the backend we just created.
Open
src/App.jsin your React application and modify it as follows:import React, { useEffect, useState } from 'react'; import axios from 'axios'; const App = () => { const [items, setItems] = useState([]); useEffect(() => { const fetchItems = async () => { const response = await axios.get('http://localhost:5000/api/items'); setItems(response.data); }; fetchItems(); }, []); return ( <div> <h1>Items from Cosmos DB</h1> <ul> {items.map(item => ( <li key={item.id}>{JSON.stringify(item)}</li> ))} </ul> </div> ); }; export default App;Start your React application in a new terminal window:
npm start
Conclusion
Congratulations! You have successfully built a web application using React connected to Azure Cosmos DB. This tutorial covered the entire process from setting up Cosmos DB to creating a React frontend that fetches data from your backend.
As you continue to develop your application, consider expanding its features by adding forms for data entry, implementing user authentication, or exploring other functionalities provided by Cosmos DB.
For more advanced topics, check out the Azure Cosmos DB documentation and the React documentation to enhance your web development skills.
Happy coding!
Connect with SkillBakery Studios
Explore more tutorials, tools, and resources:
Posted by SkillBakery Studios


No comments:
Post a Comment