Home > Software design >  how keep data after refreshing. javascript
how keep data after refreshing. javascript

Time:03-29

hey guys can you explain me why i keep losing my sections after refreshing the page)? this is my section ,i need to keep it ,i do it correctly,, i check,them in below you can see the forEach where i return it ,,, but basically ,after refreshing i lose my section ,

here is code : https://jsfiddle.net/adulik/8sqbcox2/32/

 function createTaskInput(listName) {
   //checking if storage is empty we add empty array
   if (localStorage.getItem('sections') === null) {
       localStorage.setItem('sections', '[]')
   }


   const form = createElement('form', '', 'task-form');
   const input = createElement('input', '');
   const button = createElement('button', '');
   const id = `task-${listName}`;
   input.name = 'task';
   input.id = id;
   button.innerText = 'Add';


   let sections_array = JSON.parse(localStorage.getItem('sections'))
   sections_array.push(listName)
   localStorage.setItem('sections', JSON.stringify(sections_array))

   sections_array.forEach((section)=>{
       console.log("section",section)
       updateStyle()
   })

   button.addEventListener('click', function (event) {
       event.preventDefault();
       addTaskListItem(id);
   });

   form.append(input);
   form.append(button);


   return form;
}

CodePudding user response:

You can storage the data in localstorage, then create a function that get the array from localstorage and put it in divs. also you can call the function in window.load

CodePudding user response:

This is possible with window.localStorage or window.sessionStorage. The difference is that sessionStorage lasts for as long as the browser stays open, localStorage survives past browser restarts. The persistence applies to the entire web site not just a single page of it.

When you need to set a variable that should be reflected in the next page(s), use:

var someVarName = "value";
localStorage.setItem("someVarKey", someVarName);

And in any page (like when the page has loaded), get it like:

var someVarName = localStorage.getItem("someVarKey");

.getItem() will return null if no value stored, or the value stored.

Note that only string values can be stored in this storage, but this can be overcome by using JSON.stringify and JSON.parse. Technically, whenever you call .setItem(), it will call .toString() on the value and store that.

MDN's DOM storage guide (linked below), has workarounds/polyfills, that end up falling back to stuff like cookies, if localStorage isn't available.

It wouldn't be a bad idea to use an existing, or create your own mini library, that abstracts the ability to save any data type (like object literals, arrays, etc.).

  • Related