2

I am building an application that will load bus schedules into local storage, then based on a search term provides the stops on the bus schedule. It works by clicking the load button and sending the information to local storage. Then you search a route name, and the stops information will be displayed into results. When I run in a browser my data is not loading into local storage when I press load.

<html>
<head>
<script type="text/javascript">

/**
 * A JSON string that holds data. There is no problem with the JSON string
 * @type {String}
  */

    var busSchd = '{"Routes": [{"routeName": "Milledge","stops":[{"Stop 1":"Main Library","Stop 2":"Clarke Central","Stop 3":"Five Points South","Stop 4":"Five Points North","Stop 5":"Waddell"}]},{"routeName": "Orbit","stops":[{"Stop 1":"Main Library","Stop 2":"Clarke Central","Stop 3":"Five Points South","Stop 4":"Five Points North","Stop 5":"Waddell"}]},{"routeName": "East West","stops":[{"Stop 1":"East Campus Deck","Stop 2":"Creswell Hall","Stop 3":"Hull St Deck","Stop 4":"Main Library","Stop 5":"Joe Frank Harris"}]}]}';

    
const load = () => {
    let data = JSON.parse(busSchd);
    console.log("a");
for (var i = 0; i < data.Routes.len;)
     {
         let route = data.Routes[i];
         let routeStr = route.routeName;
         localStorage.set(routeStr, JSON.stringify(route.stops));
      }

};

    const clicked = () => {
     
       var search = document.getElementById("search");
       var results = localStorage.getItem("search");

      if (results === null) {
        document.getElementById("result").innerHTML = "<b>There are no results for that route name.</b>";
      } else {
        var stops = results;
        var output = '';
        for (var key in stops[0]) {
          output = output + '<b>' + key + '</b> : ' + stops[0][key] + '<br>';
        }
        document.getElementById("result").innerHTML = output;
      }
    };
  </script>
</head>
<body>
  <input type="button" value="Load Route Data" id="load" onclick="load();">
  <br>
  <br>
  <input type="text" id="search"><input type="button" value="Find Route" id="submit" onclick="clicked();"><br>
  <br><br>
  <div id="result">
  </div>
</body>
</html>

1 Answers1

0

There were a few mistakes within your code which prevented you from saving to localStorage. Here are some pointers.

  • Use localStorage.setItem() to save and localStorage.getItem() to retrieve data.
  • There's no need for creating a localStorage item for each bus route. LocalStorage can handle quite some data, depending on the browser and user browser settings. See What is the max size of localStorage values? for more info.
  • I'd simplify your data structure. Why put stops data into an array and then into an object? I've simplified this in my example.
  • When iterating over items use for (var i = 0; i < data.Routes.length; i++) { // your code here } another alternative is to user .map when iterating over items within an array.

Here's how to load data and save it to localStorage and into the app.

let BusSchdDataFromLocalStorage = [];

const load = () => {
  // access localStorage and save the result in data 
  let data = JSON.parse(localStorage.getItem('routesInfo'));
  if (data === null) {
    // if no data is present, save InitialBusScheduleData to localStorage
    localStorage.setItem('routesInfo', JSON.stringify(InitialBusScheduleData));
  }

  // Now that data is present in localStorage, read it.
  data = JSON.parse(localStorage.getItem('routesInfo'));
  if (data.Routes.length > 0) {
    // if routes are present, save its data to a global var in our app
    BusSchdDataFromLocalStorage = data;
    statusEl.innerHTML = 'localStorage data present'
  } else {
    statusEl.innerHTML = 'localStorage data absent'
  }
};

Here's how the search part works.

const search = () => {
  const searchString = document.querySelector('#search').value;
  // data from localStorage is present in the variable below 
  const routes = BusSchdDataFromLocalStorage.Routes;

  // Filter route data based on the search input. 
  const busStopInfo = routes.reduce((stops, route) => {
    return (route.routeName.toLowerCase() === searchString.toLowerCase()) ? route.stops : stops;
  }, []);
  const stops = Object.keys(busStopInfo);
  // map over the stops and return the html structure with the stop number and the value
  const results = stops
    .map((stop) => '<div>' + stop + ' - ' + busStopInfo[stop] + '</div>')
    .join('');
  // add the html result to the result div.
  resultEl.innerHTML = results.length > 0 ? results : 'No route found with that name.';
};

If you'd like to see the code in action. Here's a JSFiddle.

Roy Scheffers
  • 3,832
  • 11
  • 31
  • 36