Search code examples
javascriptlocal-storagepreload

How can I print it out when data is added other than location.reload for localstorage?


I am storing the data with localstorage. But I have a problem like this. When a new data is added, that data does not appear before refreshing the page.

So, how can I print it out when data is added other than location.reload for localstorage?

// Add Button

                    <a style="cursor: pointer;" class="text-secondary  no-decoration" id="bookmark" data-id="<?= $this->detail->id; ?>" data-url="<?= $this->detail->articles_sef_link; ?>" data-date="<?= H::timeConvert($this->detail->created_at); ?>" data-title="<?= $this->detail->articles_title; ?>" data-img="<?= $this->detail->url; ?>" data-user="<?= $this->detail->fname;?> <?= $this->detail->lname; ?>" data-tooltip="Okunmadı olarak işaretle" data-tooltip-location="bottom"><i class="far fa-flag" style="font-size: 21px"></i></a>

// Add mark as read list $('#bookmark').click(function(){

$('#iconHidden').hide();
$('#iconShow').show();

    // Get Information articles
    let id         = $(this).data("id");
    let sef_link   = $(this).data("url");
    let created_at = $(this).data("date");
    let title      = $(this).data("title");
    let img        = $(this).data("img");
    let fullname   = $(this).data("user");


    array_item.push({id,sef_link,created_at,title,img,fullname});
    localStorage.setItem("array_item", JSON.stringify(array_item));
    location.reload();


    //console.log(array_item);

});

Solution

  • Codepen: Codepen example: Dynamic content using local storage

    This is a code example. There are three buttons which add a new bookmark to your local storage. The fourth button clears the storage.

    The bookmarks are listed in the table dynamically.

    After clicking a button the function addData is called. This function adds the new bookmark to the local storage. After that, this function calls another function updateTable. updateTable updates the table content (element with the id content). For this purpose it iterates through the bookmark array and calls addTableRow which adds a new table row to the table body for all bookmarks.

    Please notice: In this solution I cleared the table content when adding a new bookmark to the local storage. But this depends on your specific needs. You could also simply append the new added bookmark to the table instead of deleting the old content and redraw the complete bookmark array.

    HTML:

    <button onclick="button1()">Add bookmark 1</button>
    <button onclick="button2()">Add bookmark 2</button>
    <button onclick="button3()">Add bookmark 3</button>
    <button onclick="clearLocalStorage()">Clear local storage</button>
    
    <table>
      <thead>
        <tr>
          <td>Created</td>
          <td>Link</td>
          <td>Title</td>
        </tr>
      </thead>
      <tbody id="content">
        <!-- Dynamic content -->
      </tbody>
    </table>
    

    CSS:

    table{
      margin-top: 40px;
      background: #dedede;
    }
    
    td{
      min-width: 100px;
    }
    
    thead > tr > td{
      font-weight:  bold;
    }
    

    JS:

    function button1(){
      addData('01.01.1980', 'my-page.com', 'My page');
    }
    function button2(){
      addData('03.09.1990', 'your-page.com', 'Your page');
    }
    function button3(){
      addData('04.11.2010', 'our-page.com', 'Our page');
    }
    
    function clearLocalStorage(){
      localStorage.setItem("bookmarks", JSON.stringify([]));
      updateTable();
    }
    
    function addData(created, link, title){
      // Get bookmarks
      let bookmarks = JSON.parse(localStorage.getItem("bookmarks"));
      // When this object do not exist, create a new array
      if(bookmarks === undefined || bookmarks === null) bookmarks = new Array();
      console.log(bookmarks);
      bookmarks.push({created, link, title});
      // Save the new bookmark in the local storage
      localStorage.setItem("bookmarks", JSON.stringify(bookmarks));
      // Update the table which displays the bookmarks
      updateTable();
    }
    
    function updateTable(){
      // Get all bookmarks of the local storage
      let bookmarks = JSON.parse(localStorage.getItem("bookmarks"));
      console.log(bookmarks);
      // Get the DOM element which displays the bookmarks dynamically
      let content = document.getElementById('content');
      // Delete the current content
      content.innerHTML = '';
      // Iterate through the bookmark array and call the function
      // "addTableRow" for alle element in the array.
      bookmarks.forEach(bookmark => {
        addTableRow(content, bookmark);
      });
    }
    
    function addTableRow(content, data){
      // Create a new table row
      let newRow = document.createElement('tr');
      // Create new table cells
      let created = document.createElement('td');
      created.innerHTML = data.created;
      let link = document.createElement('td');
      link.innerHTML = data.link;
      let title = document.createElement('td');
      title.innerHTML = data.title;
      // Append the table cells to the row
      newRow.appendChild(created);
      newRow.appendChild(link);
      newRow.appendChild(title);
      // Append the table row to the content
      content.appendChild(newRow);
    }