Home > Back-end >  Local storage with api, vanilla js
Local storage with api, vanilla js

Time:02-18

To make this short and sweet my code is

const searchBox = document.querySelector(".search-box");
searchBox.addEventListener("keypress", setQuery);

function setQuery(e) {
  if (e.keyCode == 13) {
    getResults(searchBox.value);
    searchBox.value = "";
  }
}

function getResults(query) {
  localStorage.setItem("location", searchBox.value);
  let storedItem = localStorage.getItem("location");
  console.log(storedItem);
  fetch(`${api.base}weather?q=${storedItem}&units=imperial&APPID=${api.key}`)
    .then((weather) => {
      return weather.json();
    })
    .then(displayResults);
}

This all works great and the city that is typed into the search box is stored into the local storage just fine and if page is refreshed I can look in the google chrome app section and see it still in local storage.

After the page refresh tho the app resets to the default landing page.

I'm thinking I need to use something like window.onload = function()

the problem is if I'm setting the storedItem I can't access outside of the getResults function.

any suggestions would be appreciated!

CodePudding user response:

  • Remove localStorage.setItem("location", searchBox.value); from getResults() and add it to setQuery().

  • Next, add this to getResults()

    let qry = query == undefined ? 
    localStorage.getItem("location") : query;
    

    This means if there isn't any query passed to getResults(query) then get the value from localStorage under the key "location".

  • Finally bind the DOMContentLoaded event to document and getResults() as event handler,

    document.addEventListener('DOMContentLoaded', getResults)  
    

const searchBox = document.querySelector(".search-box");
searchBox.addEventListener("keypress", setQuery);

function setQuery(e) {
  if (e.keyCode == 13) {
    getResults(searchBox.value);
    searchBox.value = "";
    localStorage.setItem("location", searchBox.value);
  }
}

function getResults(query) {
  let qry = query == undefined ? localStorage.getItem("location") : query;
  console.log(qry);
  fetch(`${api.base}weather?q=${qry}&units=imperial&APPID=${api.key}`)
    .then((weather) => {
      return weather.json();
    })
    .then(displayResults);
};

document.addEventListener('DOMContentLoaded', getResults)

  • Related