Skip to content

Instantly share code, notes, and snippets.

@cfigueiroa
Created June 14, 2023 16:47
Show Gist options
  • Save cfigueiroa/5de6c9013525708108074ab13c63997b to your computer and use it in GitHub Desktop.
Save cfigueiroa/5de6c9013525708108074ab13c63997b to your computer and use it in GitHub Desktop.
solucao1
// 1 - Crie uma interface UserData para o formulário abaixo
// 2 - Crie uma variável global UserData no window, ela será um objeto qualquer
// 3 - Adicione um evento de keyup ao formulário
// 4 - Quando o evento ocorrer adicione a {[id]: value} ao UserData
// 5 - Salve UserData no localStorage
// 6 - Crie uma User Type Guard, para verificar se o valor de localStorage é compatível com UserData
// 7 - Ao refresh da página, preencha os valores de localStorage (caso seja UserData) no formulário e em /window.UserData
const app = document.getElementById("app");
if (app && app instanceof HTMLDivElement) {
const html = String.raw;
const template = html`
<style>
body {
font-size: 1.25rem;
font-family: sans-serif;
margin: 2rem;
}
label {
display: block;
margin-bottom: 0.5rem;
}
input {
font-size: 1.5rem;
margin-bottom: 1rem;
padding: 0.5rem;
min-width: 50vw;
max-width: 100%;
}
</style>
<form action="" id="form">
<label for="nome">Nome</label>
<input type="text" id="nome" name="nome" />
<label for="email">Email</label>
<input type="email" id="email" name="email" />
<label for="cpf">CPF</label>
<input type="text" id="cpf" name="cpf" />
</form>
`;
app.innerHTML = template;
}
interface UserData {
nome?: string;
email?: string;
cpf?: string;
}
interface Window {
UserData: UserData;
}
const UserData: UserData = {};
window.UserData = UserData;
const form = document.getElementById("form");
if (form && form instanceof HTMLFormElement) {
form.addEventListener("keyup", addId);
}
function addId(e: Event) {
if (e instanceof KeyboardEvent) {
if (e.target && e.target instanceof HTMLInputElement) {
const { id, value } = e.target;
if (isValidProperty(id)) {
UserData[id] = value;
if (value === "") {
delete UserData[id];
}
if (Object.keys(UserData).length) {
localStorage.setItem("UserData", JSON.stringify(UserData));
} else {
if (localStorage.getItem("UserData")) {
localStorage.removeItem("UserData");
}
}
}
}
}
}
function isValidProperty(key: string): key is keyof UserData {
return key === "nome" || key === "email" || key === "cpf";
}
window.addEventListener("DOMContentLoaded", () => {
const storedUserData = localStorage.getItem("UserData");
if (storedUserData) {
try {
const parsedUserData = JSON.parse(storedUserData);
if (isUserData(parsedUserData)) {
Object.assign(UserData, parsedUserData);
populateFormFields(parsedUserData);
}
} catch (error) {
console.error("Error parsing UserData from localStorage:", error);
}
}
});
function isUserData(data: any): data is UserData {
return (
typeof data === "object" &&
(data.nome === undefined || typeof data.nome === "string") &&
(data.email === undefined || typeof data.email === "string") &&
(data.cpf === undefined || typeof data.cpf === "string")
);
}
function populateFormFields(userData: UserData) {
if (form && form instanceof HTMLFormElement) {
for (const key in userData) {
if (key in userData && isValidProperty(key)) {
const input = form.elements.namedItem(key);
if (input instanceof HTMLInputElement) {
input.value = userData[key] || "";
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment