let user input and view grades and fetch them if available from json, and store the grades in json in svelte in javascript

svelte, javascript, json, fetch, user-input

index.tsx

To let the user input and view grades, we can create a form component in Svelte that allows users to enter their grades. We can then store the grades in a JSON object and use the `localStorage` API to persist the data between sessions. Here is an example of how to do this:

```html
<!-- GradeForm.svelte -->

<script>
  const grades = { subject: '', grade: '' };

  const handleSubmit = (event) => {
    event.preventDefault();

    const grade = {
      subject: grades.subject,
      grade: grades.grade
    };

    localStorage.setItem('grades', JSON.stringify(grade));
  };
</script>

<form on:submit={handleSubmit}>
  <label>
    Subject:
    <input type="text" bind:value={grades.subject}>
  </label>

  <label>
    Grade:
    <input type="text" bind:value={grades.grade}>
  </label>

  <button type="submit">Save</button>
</form>
839 chars
35 lines

To fetch the grades from JSON, we can make a GET request using the fetch API and then parse the JSON response. Here is an example of how to do this:

index.tsx
fetch('grades.json')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));
134 chars
5 lines

Finally, to store the grades in JSON, we can create a JSON object and use the JSON.stringify method to convert it to a string. We can then store the string in local storage by calling the setItem method on the localStorage object. Here is an example of how to do this:

index.tsx
const grades = [
  { subject: 'Math', grade: 'A' },
  { subject: 'Science', grade: 'B' },
  { subject: 'English', grade: 'C' }
];

localStorage.setItem('grades', JSON.stringify(grades));
187 chars
8 lines

This will store the grades array in local storage under the key 'grades'. To retrieve the grades from local storage, we can use the getItem method like this:

index.tsx
const grades = JSON.parse(localStorage.getItem('grades'));
59 chars
2 lines

related categories

gistlibby LogSnag