skip to Main Content

I’m trying to write a simple program for a teacher. This program has 3 inputs where the teacher manually enters the students’ information (name, surname and starting date). However, after entering the information, it disappears when I refresh the screen or close and reopen the program. How can I solve this problem?

import React, { useState, useEffect } from "react";
import "./App.css";

function App() {
  const [students, setStudents] = useState([]);
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  const [startDate, setStartDate] = useState("");
  const [endDate, setEndDate] = useState("");

  useEffect(() => {
    const storedStudents = localStorage.getItem("students");
    console.log("Stored Students:", storedStudents);
    if (storedStudents) {
      setStudents(JSON.parse(storedStudents));
    }
  }, []);

  useEffect(() => {
    localStorage.setItem("students", JSON.stringify(students));
  }, [students]);

  const formatDate = (date) => {
    const options = { year: "numeric", month: "numeric", day: "numeric" };
    return new Date(date).toLocaleDateString("en-US", options);
  };

  const calculateEndDateAndSave = () => {
    const startDateObj = new Date(startDate);
    const endDateObj = new Date(
      startDateObj.getTime() + 4 * 7 * 24 * 60 * 60 * 1000
    );

    setEndDate(formatDate(endDateObj));

    const newStudent = {
      firstName: firstName,
      lastName: lastName,
      startDate: formatDate(startDate),
      endDate: formatDate(endDateObj),
    };

    setStudents([...students, newStudent]);
    setFirstName("");
    setLastName("");
    setStartDate("");
  };

  const deleteStudent = (index) => {
    const newStudents = [...students];
    newStudents.splice(index, 1);
    setStudents(newStudents);
  };

  return (
    <div className="mainPage">
      <h1>Student Information</h1>
      <label>
        First Name:
        <input
          type="text"
          value={firstName}
          onChange={(e) => setFirstName(e.target.value)}
        />
      </label>
      <br />
      <label>
        Last Name:
        <input
          type="text"
          value={lastName}
          onChange={(e) => setLastName(e.target.value)}
        />
      </label>
      <br />
      <label>
        Start Date:
        <input
          type="date"
          value={startDate}
          onChange={(e) => setStartDate(e.target.value)}
        />
      </label>
      <br />
      <div className="button-container">
        <button onClick={calculateEndDateAndSave}>
          Calculate and Save End Date
        </button>{" "}
      </div>
      <br />
      <h2>Registered Students</h2>
      <ul>
        {students.map((student, index) => (
          <li key={index}>
            <b>
              {student.firstName} {student.lastName}
            </b>{" "}
            --- <b>Start Date:</b> {student.startDate}, <b>End Date:</b>{" "}
            {student.endDate}
            <button
              style={{ marginLeft: "10px" }}
              onClick={() => deleteStudent(index)}
            >
              Delete
            </button>{" "}
          </li>
        ))}
      </ul>
    </div>
  );
}

export default App;

2

Answers


  1. Chosen as BEST ANSWER

    I solved the problem.

    In this code, the "getStoredStudents" function will retrieve the data from localStorage when the page is loaded and update the state with "setStudents". Also, when you add or delete students, I update localStorage with the "updateLocalStorage" function. This way you can keep localStorage updated if there are any changes.

    You can see the answer below.

    import React, { useState, useEffect } from "react";
    import "./App.css";
    
    function App() {
      const [students, setStudents] = useState([]);
      const [firstName, setFirstName] = useState("");
      const [lastName, setLastName] = useState("");
      const [startDate, setStartDate] = useState("");
      const [endDate, setEndDate] = useState("");
    
      const getStoredStudents = () => {
        const storedStudents = localStorage.getItem("students");
        if (storedStudents) {
          setStudents(JSON.parse(storedStudents));
        }
      };
    
      useEffect(() => {
        getStoredStudents();
      }, []);
    
      const updateLocalStorage = (newStudents) => {
        localStorage.setItem("students", JSON.stringify(newStudents));
      };
    
      const formatDate = (date) => {
        const options = { year: "numeric", month: "numeric", day: "numeric" };
        return new Date(date).toLocaleDateString("en-US", options);
      };
    
      const calculateEndDateAndSave = () => {
        const startDateObj = new Date(startDate);
        const endDateObj = new Date(startDateObj.getTime() + 4 * 7 * 24 * 60 * 60 * 1000);
    
        setEndDate(formatDate(endDateObj));
    
        const newStudent = {
          firstName: firstName,
          lastName: lastName,
          startDate: formatDate(startDate),
          endDate: formatDate(endDateObj),
        };
    
        const newStudents = [...students, newStudent];
        setStudents(newStudents);
        updateLocalStorage(newStudents);
    
        setFirstName("");
        setLastName("");
        setStartDate("");
      };
    
      const deleteStudent = (index) => {
        const newStudents = [...students];
        newStudents.splice(index, 1);
        setStudents(newStudents);
        updateLocalStorage(newStudents);
      };
    
      return (
        <div className="mainPage">
          <h1>Student Information</h1>
          {/* ... (other input ve button elements) ... */}
        </div>
      );
    }
    
    export default App;
    

  2. After refreshing a page, the data on the browser and the thing you input will disappear that’s why you need to store it in browser example using : cookie,localStorage etc so even if you refresh the page the data is still in the browser you just need to make a way to display the data in the page

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search