Skip to content

Commit

Permalink
Merge pull request #4 from Valik3201/feedback-form
Browse files Browse the repository at this point in the history
Saved and restored form state with local storage
  • Loading branch information
Valik3201 authored Nov 16, 2023
2 parents 85b00a7 + 6c3e0d8 commit ec70566
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/js/03-feedback.js
Original file line number Diff line number Diff line change
@@ -1 +1,30 @@
import throttle from 'lodash/throttle';

const form = document.querySelector('.feedback-form');
const localStorageKey = 'feedback-form-state';

const storedData = JSON.parse(localStorage.getItem(localStorageKey)) ?? {};
form.elements.email.value = storedData.email ?? '';
form.elements.message.value = storedData.message ?? '';

const updateLocalStorage = event => {
const { name, value } = event.target;
// const storedData = JSON.parse(localStorage.getItem(localStorageKey)) ?? {};
storedData[name] = value;

localStorage.setItem(localStorageKey, JSON.stringify(storedData));
};

form.addEventListener('input', throttle(updateLocalStorage, 500));

form.addEventListener('submit', event => {
event.preventDefault();

console.log('Submitted Data:', {
email: form.elements.email.value || 'N/A',
message: form.elements.message.value || 'N/A',
});

localStorage.removeItem(localStorageKey);
form.reset();
});

0 comments on commit ec70566

Please sign in to comment.