Home > Mobile >  I executed this code, But it showed type error like this "TypeError: Cannot read properties of
I executed this code, But it showed type error like this "TypeError: Cannot read properties of

Time:08-20

I executed this code, But it showed a type error like this "TypeError: Cannot read properties of undefined (reading 'map')"

I implement a crud application to manage student data. This is the data retrieving code. I used the database as mongo DB databases. But when is being executed the code this type of error showed.

"TypeError: Cannot read properties of undefined (reading 'map')"

Home.jsx

import { useState, useEffect } from "react";
import axios from "axios";

export default function Home() {
  const [student, setStudent] = useState("");
  const [totage, setTotal] = useState("");

  useEffect(() => {
    axios.get("http://localhost:5000/student").then((res) => {
      if (res.data.success) {
        setStudent(res.data.existingData);
      }
    });
  }, []);

  const onDelete = (id) => {
    axios.delete(`http://localhost:5000/student/${id}`).then((res) => {
      if (res.data.success) {
      }
      alert("Delleted Success");
      window.location = "/";
    });
  };

  const calculate = () => {
    var total = 0;

    {
      student.map((data) => {
        total = total   parseInt(data.age);
      });
    }

    console.log(total);
    setTotal(total);
  };

  return (
    <div>
      <h1>View Students</h1>
      <a href="/add">
        <button>Add Students</button>
      </a>
      <a href="/register">
        <button>Register</button>
      </a>
      <a href="/login">
        <button>Login</button>
      </a>
      <br></br>
      <br></br>
      <table border="2">
        <thead>
          <tr>
            <td>#</td>
            <td>Name</td>
            <td>Age</td>
            <td>City</td>
            <td>Update</td>
            <td>Delete</td>
          </tr>
        </thead>
        <tbody>
          {student.map((data, index) => {
            return (
              <tr key={index}>
                <th scope="row">{index   1}</th>
                <td>{data.name}</td>
                <td>{data.age}</td>
                <td>{data.city}</td>
                <td>
                  <a href={`/edit/${data._id}`}>
                    <button>Update</button>
                  </a>
                </td>
                <td>
                  <button type="submit" onClick={() => onDelete(data._id)}>
                    Delete
                  </button>
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
      <br></br>
      <a onClick={calculate}>
        <button>Calulate</button>
      </a>
      <h1>Total age - {totage}</h1>
    </div>
  );
}

CodePudding user response:

I think in the code you are missing an array in the use state. Please change it in the below format.

 const [student, setStudent] = useState([]);
  • Related