1

So I'm trying to store recent searches as an array in local storage. And display them every X seconds. The function works but when I refresh page, it doesn't work. (Is this because I'm running the site locally for development reasons? Or does this not matter?)

Here is the Javascript

function customDeal1() {
var myArray = [];
var dal = $('#search').val();
myArray.unshift(dal);
localStorage.setItem("drinksss", JSON.stringify(myArray));
var searchText = JSON.parse(localStorage.getItem("drinksss" || "[]"));
var matchArray = findDeals(searchText, name).slice(0,1);

  const html = matchArray.map(place => {
    const regex = new RegExp(searchText);
    const nameName = place.name.replace(regex, `<span class="hl">${searchText}</span>`);
         var shop = place.url.replace(/(centra)|[^]/g, '$1').replace(/^\w/, c => c.toUpperCase());
         var shop1 = place.url.replace(/(tesco)|[^]/g, '$1').replace(/^\w/, c => c.toUpperCase());
         var shop2 = place.url.replace(/(aldi)|[^]/g, '$1').replace(/^\w/, c => c.toUpperCase());
         var shop3 = place.url.replace(/(lidl)|[^]/g, '$1').replace(/^\w/, c => c.toUpperCase());
         var shop4 = place.url.replace(/(supervalu)|[^]/g, '$1').replace(/^\w/, c => c.toUpperCase());
    return `

            <img src="${place.imgurl}" alt="Drink Image">
            <h5>${nameName}</h5>
            <p>${(place.price)} ${shop} ${shop1} ${shop2} ${shop3} ${shop4}</p>

    `;
  }).join('') || '<li> No Searches Found </li>';
  deal2.innerHTML = html; 

};
const deal2 = document.querySelector('.deal1');
setInterval(customDeal1,10000);
  • 2
    Can you elaborate on “doesn’t work”? – schteppe May 31 '20 at 10:21
  • You might want to look at: [Persistent storage on client side](https://stackoverflow.com/questions/4278467/persistent-storage-on-client-side) or [Persist javascript variables across pages](https://stackoverflow.com/questions/1981673/persist-javascript-variables-across-pages) – lurker May 31 '20 at 10:21
  • So when I refresh the page, the script runs and shows a recent search (which is the first item in the JSON file). When I search and stay on the page it changes to my last search which is what I want but when you refresh it doesn't remember my last search and displays the first item in the JSON file as the "searchText"value when used empty displays the first listing in the JSON file – valeriu7474 May 31 '20 at 10:37

0 Answers0