Estoy tratando de hacer un rastreador de dinero, pero cada vez que actualizo desaparecen. ¿Alguien sabe cómo puedo usar el almacenamiento local para que se queden? Intenté usar el almacenamiento local, pero no puedo entenderlo y es muy confuso para mí. Lápiz de código: https://codepen.io/jordandevelops/pen/wvPWzxL
const table = document.getElementById('contentTable'), inputText = document.getElementById('inputText'), inputPrice = document.getElementById('inputPrice'), inputDate = document.getElementById('inputDate'), form = document.getElementById('form'); form.addEventListener('submit', (e) => { e.preventDefault(); addNewItem(); }); function addNewItem(){ if(inputPrice.value == ''){ alert('Error, please enter price of purchase.'); return; } if(inputDate.value == ''){ alert('Error, please enter date of purchase.'); return; } let newTr = document.createElement('tr'); let newTd1 = document.createElement('td'); let newTd2 = document.createElement('td'); let newTd3 = document.createElement('td'); table.appendChild(newTr); newTr.appendChild(newTd1); newTr.appendChild(newTd2); newTr.appendChild(newTd3); newTr.classList.add('createdTr') newTd1.classList.add('tdName'); newTd2.classList.add('tdPrice'); newTd3.classList.add('tdDate'); newTd1.innerText = inputText.value; newTd2.innerText = `$${inputPrice.value}`; newTd3.innerText = inputDate.value; }En el almacenamiento local, almacena la estructura de datos en formato JSON (no el HTML que contiene los datos).
Para almacenar datos:
function addNewItem(){ //... check and validate the input like you do // grab the current local storage or create an empty container let theData = localStorage.get('theData') || "[]"; theData = JSON.parse(theData); // get it into object format //add to it theData.push({text: inputText.value, price: inputPrice.value, date: inputDate.value}); // store that back into local storage as a string localStorage.set('theData', JSON.stringify(theData)); //... continue on with your codePara recuperar los datos, hazlo al cargar la página.
document.addEventListener('DOMContentLoaded', () => { let theData = localStorage.get('theData') || "[]"; JSON.parse(theData).forEach(d => { // ... this is where you take the existing local storage list and populate it into your HTML. // You can leverage your existing addNewItem function but you'll need to update it to allow for sending input directly into it. })El almacenamiento local puede funcionar bien, pero recomendaría usar IndexedDB si desea almacenar datos como este.
IndexedDB es incluso más complicado que el almacenamiento local en algunos aspectos, pero hay una gran biblioteca llamada "Dexie" que lo hace mucho más fácil. Puedes verlo aquí: https://dexie.org/
Con Dexie, puede guardar, restaurar y consultar sus datos. Tomará un poco de tiempo experimentar y aprender a hacerlo, pero será una gran herramienta para tener en su caja de herramientas.