Developing Web App using React Cosmos DB - Add Records - SkillBakery Studios

Breaking

Post Top Ad

Post Top Ad

Friday, July 10, 2026

Developing Web App using React Cosmos DB - Add Records

Developing Web App using React Cosmos DB - Add Records

Screenshot from the tutorial
Screenshot from the tutorial

Developing a Web App using React and Cosmos DB: Adding Records

In the rapidly evolving world of web development, creating robust and scalable applications is paramount. In this blog post, we will explore how to develop a web application using React and Microsoft Azure's Cosmos DB, focusing specifically on the process of adding records to the database. This tutorial is inspired by the YouTube video titled "Developing Web App using React Cosmos DB - Add Records."

What is React?

React is a popular JavaScript library for building user interfaces, especially for single-page applications where a seamless user experience is crucial. It allows developers to create reusable UI components, resulting in efficient and maintainable code.

What is Cosmos DB?

Azure Cosmos DB is a globally distributed, multi-model database service designed for high availability, scalability, and low latency. It supports various data models including document, key-value, graph, and column-family, making it an excellent choice for modern web applications.

Prerequisites

Before we get started, ensure that you have the following tools and technologies set up:

  1. Node.js: Ensure you have Node.js installed on your machine. You can download it from the official website.
  2. React: Familiarity with React concepts will be beneficial.
  3. Azure Account: If you don't have one, create a free Azure account here.
  4. Cosmos DB Setup: Create a Cosmos DB instance in your Azure portal. You can follow the official documentation for setup instructions.

Setting up the React Application

Create a New React App

To begin, we will create a new React application using Create React App. Open your terminal and run:

npx create-react-app my-cosmos-app
cd my-cosmos-app

Install Axios

We will use Axios for making HTTP requests to our Cosmos DB API. Install Axios by running:

npm install axios

Connecting to Cosmos DB

Setting Up the API

To interact with Cosmos DB, we need an API to handle our requests. You can use Azure Functions or any backend framework. For simplicity, we will assume you have already set up an API to handle POST requests for adding records. Here’s a basic example of a Node.js Express server that connects to Cosmos DB:

const express = require('express');
const { CosmosClient } = require('@azure/cosmos');

const app = express();
app.use(express.json());

const endpoint = "YOUR_COSMOS_DB_ENDPOINT";
const key = "YOUR_COSMOS_DB_KEY";
const databaseId = "YOUR_DATABASE_ID";
const containerId = "YOUR_CONTAINER_ID";

const client = new CosmosClient({ endpoint, key });

app.post('/addRecord', async (req, res) => {
    const { id, name } = req.body;

    const { container } = await client.database(databaseId).container(containerId);
    const { resource } = await container.items.create({ id, name });

    res.status(201).json(resource);
});

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
});

Test the API

Make sure your API is running and accessible. You can use tools like Postman to send a POST request to http://localhost:5000/addRecord with the following JSON body:

{
    "id": "1",
    "name": "Sample Record"
}

Adding Records in the React App

Create a Form Component

In your React application, we will create a simple form to add records. Create a new component called AddRecord.js:

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

const AddRecord = () => {
    const [id, setId] = useState('');
    const [name, setName] = useState('');

    const handleSubmit = async (e) => {
        e.preventDefault();
        try {
            const response = await axios.post('http://localhost:5000/addRecord', { id, name });
            console.log('Record added:', response.data);
        } catch (error) {
            console.error('Error adding record:', error);
        }
    };

    return (
        <form onSubmit={handleSubmit}>
            <input type="text" placeholder="ID" value={id} onChange={(e) => setId(e.target.value)} />
            <input type="text" placeholder="Name" value={name} onChange={(e) => setName(e.target.value)} />
            <button type="submit">Add Record</button>
        </form>
    );
};

export default AddRecord;

Integrate the Component

Next, integrate this AddRecord component into your App.js file:

import React from 'react';
import AddRecord from './AddRecord';

const App = () => {
    return (
        <div>
            <h1>Add Records to Cosmos DB</h1>
            <AddRecord />
        </div>
    );
};

export default App;

Testing the Application

Now that everything is set up, you can start your React application:

npm start

Navigate to http://localhost:3000, where you will see the form to add records. Fill in the ID and Name fields and submit the form. If everything is correctly configured, you should see a new record added to your Cosmos DB.

Conclusion

In this tutorial, we covered the process of developing a simple web application using React and Azure Cosmos DB, focusing on adding records. By combining the power of React with the scalability of Cosmos DB, you can build robust applications that cater to a wide array of user needs.

Feel free to explore further functionalities such as retrieving records, updating them, and enhancing your application with additional features. Happy coding!

Another screenshot from the tutorial
Another view from the tutorial

Connect with SkillBakery Studios

Explore more tutorials, tools, and resources:

Posted by SkillBakery Studios

No comments:

Post a Comment

Post Top Ad