skip to Main Content

I have this block of code that I am repeating myself and it feels wrong but I can’t figure out how to write it better

      const students = localStorage.getItem("Students");
      let newStudents = [{}];
      //If we already have students in local storage we want to get those and add to them
      if (students) {
        const parseStudents = JSON.parse(students as string);
        newStudents = [
          ...parseStudents,
          {
            firstName: firstNameInput.current.value,
            familyName: familyNameInput.current.value,
            email: emailInput.current.value,
            dob: dob,
          },
        ];
        //If we don't have students just add our first student
      } else {
        newStudents = [
          {
            firstName: firstNameInput.current.value,
            familyName: familyNameInput.current.value,
            email: emailInput.current.value,
            dob: dob,
          },
        ];
      }

2

Answers


  1. The following should work without repetitions:

    const students =  JSON.parse(localStorage.getItem("Students") as string);
    const newStudents = [
      ...(students || []),
      {
        firstName: firstNameInput.current.value,
        familyName: familyNameInput.current.value,
        email: emailInput.current.value,
        dob: dob,
      }
    ]
    console.log(newStudents);
    

    Basically, if student is undefined, we just use [], so we simply start with an empty array and spread.

    Login or Signup to reply.
  2. First, let’s create a type for a student:

    type Student = {
      firstName: string;
      familyName: string;
      email: string;
      dob: string;
    };
    

    Now let’s write a function that will return as the students stored in the localStorage:

    const getStudentsFromStorage = (): Student[] => {
      try {
        const students = localStorage.getItem('Students');
        if (!students) return [];
    
        const parsedStudents = JSON.parse(students);
    
        if (!Array.isArray(parsedStudents)) return [];
    
        //You can also add a type guard here to check whether elements are actually Students
        return parsedStudents;
      } catch {
        return [];
      }
    };
    

    This function checks item existing in storage, and if the stored item is actually an array, you can also add a custom type guard to guarantee that elements of the array are Student completely.

    The last thing left is to write a function that would add the new student to the array and it can be done as follows:

    const pushStudent = (student: Student) => {
      return getStudentsFromStorage().concat(student);
    };
    

    Usage:

    let newStudents = pushStudent({
      firstName: 'name',
      familyName: 'familyname',
      email: 'email',
      dob: 'dob',
    });
    

    playground

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