user19522235
user19522235

Reputation: 19

How Do I reload Divs With Information from Local Storage?

I have entire div's loaded with content and I loaded it into the local storage, But I don't really know what I'm supposed to do with it. I want to be able to reload the page an have all the todo cards still there with of course the possibility to create a new todoCard and have that be reloaded as well. Heres what I have for the load to local storage

    // Store the todosCard in local storage
  localStorage.setItem(toDo.name, JSON.stringify({
    outerHTML: todosCard.outerHTML,
    innerHTML: todosCard.innerHTML
  }));

I tried looping and loading each card using the beforeunload EventListener, given the name i figured that wouldnt work and it didnt so then I tried Domcontent loaded and also to no avail as it prints the correct div but then it wont let me create a new todo card.

this is what I tried initially

 localStorage.setItem(toDo.name, JSON.stringify({
    outerHTML: todosCard.outerHTML,
    innerHTML: todosCard.innerHTML
  }));


    popUp.classList.remove("popUpActive");
})

document.addEventListener('DOMContentLoaded', function(event) {
    for (let i = 0; i < localStorage.length; i++) {
      const storedKey = localStorage.key(i);
      const storedValue = localStorage.getItem(storedKey);
  
      // Create a new div element and set its innerHTML with the stored value
      const todosCard = document.createElement('div');
      todosCard.innerHTML = storedValue.innerHTML;
      todosCard.outerHTML = storedValue.outerHTML;
      toDosContainer.appendChild(todosCard);
    }
  });

and after that I tried messing with the inner and outer so that on;y one was being loaded and logged and that worked in the sense it actually loaded something on refresh but not what was needed

Upvotes: 0

Views: 165

Answers (1)

Rayne Blackham
Rayne Blackham

Reputation: 119

You may consider using useStates, this would re-render your component on change.

Example:

const [data, setData] = useState(); // default to empty
setData(JSON.parse(localStorage.getItem('your-key')));

Then you can conditionally render the divs if data is present.

Upvotes: 0

Related Questions