this is my code in which I am trying to create a mern app with basic crude operations and conncting with mongoDb and its showing a white page and when i refresh its showing my UI just for a second and then again its showing the white screen again there are no errors mostly please help is any ,Thanks in advanced.

App.jsx

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

const App = () => {
  const [students, setStudents] = useState([]);
  const [newStudentId, setNewStudentId] = useState('');
  const [newStudentName, setNewStudentName] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    setLoading(true);
    axios.get('/students')
      .then(res => {
        setStudents(res.data);
        setLoading(false);
      })
      .catch(err => {
        setError(err.message);
        setLoading(false);
      });
  }, []);

  const addStudent = async () => {
    try {
      setLoading(true);
      const response = await axios.post('/students', { studentId: newStudentId, name: newStudentName });
      setStudents([...students, response.data]);
      setLoading(false);
      setNewStudentId('');
      setNewStudentName('');
    } catch (err) {
      setError(err.message);
      setLoading(false);
    }
  };

  const deleteStudent = async (studentId) => {
    try {
      setLoading(true);
      await axios.delete(`/students/${studentId}`);
      setStudents(students.filter(student => student.studentId !== studentId));
      setLoading(false);
    } catch (err) {
      setError(err.message);
      setLoading(false);
    }
  };

  return (
    <div>
      <h1>Student Management System</h1>
      <div>
        <h2>Add Student</h2>
        <form onSubmit={e => {
          e.preventDefault();
          addStudent();
        }}>
          <label>
            Student ID:
            <input type="text" value={newStudentId} onChange={e => setNewStudentId(e.target.value)} required />
          </label>
          <label>
            Name:
            <input type="text" value={newStudentName} onChange={e => setNewStudentName(e.target.value)} required />
          </label>
          <button type="submit">Add</button>
        </form>
      </div>
      <div>
        <h2>Student List</h2>
        {loading && <p>Loading...</p>}
        {error && <p>Error: {error}</p>}
        <ul>
          {students.map(student => (
            <li key={student.studentId}>
              {student.studentId}: {student.name}
              <button onClick={() => deleteStudent(student.studentId)}>Delete</button>
            </li>
          ))}
        </ul>
      </div>
    </div>
  );
};

export default App;

main.jsx

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(<App />, document.getElementById('root'));

index.js

// Import required modules
const express = require('express');
const mongoose = require('mongoose');

// Create Express app
const app = express();

// Connect to MongoDB
mongoose.connect('mongodb://127.0.0.1:27017/students', { useNewUrlParser: true, useUnifiedTopology: true });

const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  console.log("Connected to MongoDB");
});

// Define a schema for the data
const studentSchema = new mongoose.Schema({
  studentId: String,
  name: String
});
const Student = mongoose.model('students', studentSchema);

// Middleware for JSON parsing
app.use(express.json());

// Create a new student
app.post('/students', async (req, res) => {
  try {
    const newStudent = new Student({
      studentId: req.body.studentId,
      name: req.body.name
    });
    await newStudent.save();
    res.status(201).json(newStudent);
  } catch (err) {
    res.status(400).json({ message: err.message });
  }
});

// Get all students
app.get('/students', async (req, res) => {
  try {
    const students = await Student.find();
    res.json(students);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

// Get a single student by studentId
app.get('/students/:studentId', getStudent, (req, res) => {
  res.json(res.student);
});

// Update a student by studentId
app.patch('/students/:studentId', getStudent, async (req, res) => {
  if (req.body.name != null) {
    res.student.name = req.body.name;
  }
  try {
    const updatedStudent = await res.student.save();
    res.json(updatedStudent);
  } catch (err) {
    res.status(400).json({ message: err.message });
  }
});

// Delete a student by studentId
app.delete('/students/:studentId', getStudent, async (req, res) => {
  try {
    await res.student.remove();
    res.json({ message: 'Deleted student' });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

// Middleware to get a student by studentId
async function getStudent(req, res, next) {
  let student;
  try {
    student = await Student.findOne({ studentId: req.params.studentId });
    if (student == null) {
      return res.status(404).json({ message: 'Cannot find student' });
    }
  } catch (err) {
    return res.status(500).json({ message: err.message });
  }

  res.student = student;
  next();
}

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

I was experting the basic crud operations

0

There are 0 best solutions below