To let the user input grades for different subjects and store them in Svelte, we can create a form with input fields for each subject. Here's an example:
344 chars19 lines
In this example, we're using the bind
directive to bind the value of each input field to a variable in our component's state (mathGrade
, englishGrade
, and scienceGrade
). When the user clicks the "Save Grades" button, we'll call a function to store these grades in a JSON object in Svelte.
index.tsx186 chars10 lines
In this function, we're creating a new object with the grades for each subject, and then using localStorage.setItem
to save this object to the browser's local storage as a JSON string.
To fetch and use the stored grades in Svelte, we can create a computed property that reads the grades
object from local storage and returns it as an object:
index.tsx136 chars8 lines
In this computed property, we're using a try-catch block to safely parse the grades
object from local storage, and returning an empty object if parsing fails.
We can then use this grades
object in our template to display the stored grades:
137 chars6 lines
In this example, we're displaying each subject's grade as a list item in an unordered list. We're using the ||
operator to display a dash (-
) instead of a blank space if the grade for a subject is empty.
gistlibby LogSnag