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
The following should work without repetitions:
Basically, if student is undefined, we just use
[]
, so we simply start with an empty array and spread.First, let’s create a type for a student:
Now let’s write a function that will return as the students stored in the localStorage:
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:
Usage:
playground