How to connect ReactJS with MongoDB? And using getServerSideProps in fetching data

In a React application, particularly with Next.js (a popular framework for building server-side rendered React applications), you don't directly connect to MongoDB from the client-side code. Instead, you create an API route or a backend server using Next.js serverless functions, and this backend server handles the connection to MongoDB and performs database operations.

Let's go through a step-by-step example of how to set up a simple Next.js application with MongoDB and implement a basic schema:


Step 1: Install required dependencies


You'll need to install the required packages for MongoDB and Mongoose (a popular MongoDB object modeling tool) in your project. Run the following command in the root of your project to install them:

PowerShell and Linux terminal
npm install mongoose dotenv

Step 2: Set up MongoDB connection

Create a file called db.js in the root of your project to handle the MongoDB connection using Mongoose:

javascript and nodejs
// db.js import mongoose from 'mongoose';
const connectDB = async () => {
    try {
            await mongoose.connect(process.env.MONGODB_URI,
             {useNewUrlParser ; trueuseUnifiedTopologytrue, }); 
            console.log('MongoDB connected!'); 
         }catch (error) { 
                console.error('Error connecting to MongoDB:', error); 
        } 
}; 
export default connectDB;


Step 3: Set up environment variables

Create a .env.local file in the root of your project to store environment variables. Add your MongoDB connection URI to this file:

plaintext
MONGODB_URI=your-mongodb-connection-uri

Step 4: Define a schema and model

In this example, we'll define a simple schema for a "Person" with a name and age:

javascript
// models/person.js 
import mongoose from 'mongoose'
const personSchema = new mongoose.Schema({
    name: { typeStringrequiredtrue, },
    age: { typeNumberrequiredtrue, },
 });
const Person = mongoose.models.Person || mongoose.model('Person', personSchema); export default Person;

Step 5: Create an API route

Next, create an API route to handle requests from the frontend and interact with the MongoDB database:

javascript
// pages/api/persons.js
import connectDB from '../../db'
import Person from '../../models/person'
connectDB(); 
export default async function handler(req, res) {
    if (req.method === 'POST') {
       try {
            const { name, age } = req.body;
            const newPerson = new Person({ name, age 
             const savedPerson = await newPerson.save();                                      res.status(201).json(savedPerson); 
        catch (error) { 
             res.status(500).json({ error'Error saving the person to the database.' }); 
        }
     } else if (req.method === 'GET') {
        try { 
               const persons = await Person.find({}); 
               res.status(200).json(persons); } catch (error) { 
               res.status(500).json({ error'Error fetching data from the database.'});
             }
        }
 }


Step 6: Create React components

Now, you can create React components in the pages directory to interact with the API route you just created. For example:
jsx
// pages/index.js
    import { useState } from 'react'
    const Home = ({ persons }) => { 
    const [name, setName] = useState(''); 
    const [age, setAge] = useState(''); 
    const handleFormSubmit = async (e) => {
        e.preventDefault();
        try
                const response = await fetch('/api/persons', { 
                method: 'POST', headers: { 'Content-Type': 'application/json', },                 body: JSON.stringify({ name, age }), });
                if (response.ok) {// Handle success 
                    console.log('Person added successfully!');
                 } else { // Handle error 
                      console.error('Error adding person:', response.statusText);                 
             } catch (error) {
                console.error('Error adding person:', error.message); } 
             }; 
            return
            <div> 
            <h1>Persons</h1> 
                <form onSubmit={handleFormSubmit}> 
             <input type="text" placeholder="Name" value={name} onChange={(e) =>              setName(e.target.value)} /> 
    <input type="number" placeholder="Age" value={age} onChange={(e) =>                 setAge(e.target.value)} /> 
        <button type="submit">Add Person</button> 
   </form>
    <h2>All Persons</h2>
    <ul>
    {persons.map((person) => ( 
        <li key={person._id}> {person.name} ({person.age} years old) </li> 
     ))} 
    </ul>
    </div> ); 
}; 
export async function getServerSideProps() { 
    try { const response = await fetch('/api/persons');
    const persons = await response.json(); 
    return { props: { persons } };
 }catch (error) { 
    console.error('Error fetching data:', error.message);
    return { props: { persons: [] }};
   
export default Home;


. When you run the Next.js app using npm run dev