let user input grades for different subjects and store them in svelte, also fetch eventual stored values in json in svelte in javascript

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:

<form>
  <label>
    Math:
    <input type="text" bind:value={mathGrade} />
  </label>
  
  <label>
    English:
    <input type="text" bind:value={englishGrade} />
  </label>
  
  <label>
    Science:
    <input type="text" bind:value={scienceGrade} />
  </label>
  
  <button type="button" on:click={storeGrades}>Save Grades</button>
</form>
344 chars
19 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.tsx
function storeGrades() {
  const grades = {
    math: mathGrade,
    english: englishGrade,
    science: scienceGrade
  };
  
  localStorage.setItem('grades', JSON.stringify(grades));
}
186 chars
10 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.tsx
const grades = (() => {
  try {
    return JSON.parse(localStorage.getItem('grades')) || {};
  } catch (err) {
    return {};
  }
})();
136 chars
8 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:

<ul>
  <li>Math: {grades.math || '-'}</li>
  <li>English: {grades.english || '-'}</li>
  <li>Science: {grades.science || '-'}</li>
</ul>
137 chars
6 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