Saving user data after page reload

Imagine that you write a task manager. The application should work as native: work offline as well as online.


Basic concept


Our main tool in building such an application is localstorage.


With other ways to realize this, I am not familiar. The method of which I will tell I thought up myself and it seemed to me successful.


How will this work?


So, we have a list of tasks:


<ul class="tasks">
  <li class="task">
    <p class="task__text" contenteditable="true">Eggs</p>
    <input type="checkbox">
  </li>
  <li class="task">
    <p class="task__text" contenteditable="true">Breads</p>
    <input type="checkbox">
  </li>
</ul>
<button class="task__add-btn" type="button">New task</button>

We need to store and update the text of the task and the status completed / not, as well as implement the addition of a new task.


We will generate a random key for each task and use it as an identifier for each associated stored information in localstorage. By analogy, it is similar to databases.


Where to begin?


First of all, we will look whether there are already any tasks in memory. All keys will be stored in one line.


const savedTokens = localStorage.getItem('tokens');
const root = document.querySelector('.tasks');
let tokens = [];
if (savedTokens != null) {
  tokens = savedTokens.split(', ');
  // ...
}

For the time being, let's understand the addition of a new task in order to understand the concept of storing and using stored data.


When you click on add a task, a template task will appear in the list, the task text can be edited. Neper need to describe all this.


Create a function that creates an element with its contents from the data passed to it.


function getTemplate(token, data) {
  const task = document.createElement('li');
  task.classList.add('task');
  task.setAttribute('data-token', token);
  task.innerHTML = `
    <p class="task__text" contenteditable="true">${data.text}</p>
    <input type="checkbox" ${data.input == 'true' ? 'checked' : ''}>
  `;
  return task;
}

We describe the events for the button and for editing the task:


const btnAddTask = document.querySelector('.task__add-btn');
btnAddTask.addEventListener('click', function(e) {
  e.preventDefault();
  const newToken = randomToken();
  tokens.push(newToken);
  const taskData = {
    text: 'Task`s title',
    input: false
  };
  root.appendChild(getTemplate(newToken, taskData));
  updateTokens();
  updateEvent(newToken);
});

Implement the missing updateEvent and randomToken functions.


function updateEvent(token) {
  const task = root.querySelector(`[data-token="${token}"]`);
  const text = task.querySelector(`.task__text`);
  const input = task.querySelector(`input`);
  localStorage.setItem(`text-${token}`, text.innerHTML);
  localStorage.setItem(`input-${token}`, input.checked);
  text.addEventListener('input', function() {
    localStorage.setItem(`text-${token}`, text.innerHTML);
  });
  input.addEventListener('click', function() {
    localStorage.setItem(`input-${token}`, input.checked);
  });
}
function updateTokens() {
  localStorage.setItem('tokens', tokens.join(', '));
}
function randomToken() {
  return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
}

Fine! We implemented adding a task and saving it to localStorage. It remains to conclude the tasks that have already been saved.


Output saved tasks


To display tasks, it is enough to get all the keys, parse them, extract the text of the task and its status for each key. Then just create each task in root: we get a task with getTemplate and insert it into root.


 tokens.forEach(function(token) {
  const text = localStorage.getItem(`text-${token}`);
  const input = localStorage.getItem(`input-${token}`);
  root.appendChild(getTemplate(token, {
    text: text,
    input: input
  }));
  updateEvent(token);
});

In general, our simple task manager is ready. It remains to collect everything in a bunch.


Working task manager is available by reference .


Also popular now: