reuse result in ajax call

reuse result in ajax call

Hi there!

I'm using Ajax to get some data from an API. What I need to do is to use store the data into Local Storage when I call get the call back. Next time I'll update the page, I want to get the data from the Local Storage instead of geting the data from the API all the time. I do also have a timer that gives new data from the API after 1 hour. Actually, everything works fine, but my question how I can reuse (and not duplicate) the data in smart way. If you looking into the two functions 'getFromLS' and 'getFromAPI', I have not been able to figure out how to make this accessible outside one function into the other so to say..

Thanks alot!

         jQuery( navHooker). append( myItem);
         console. log( 'fetch from Local Storge..' + myItem);



     'use strict';

     // --- Parameters --- //
     var navHooker = jQuery( '#myNavigation > ul');

     // --- Check if we will use Local Storage or Live data --- //
     if ( localStorage. getItem( 'myLsItem') === null) {
         getFromAPI();
    }
     else {
         var minutes = 1000 * 60;
         var hours = minutes * 60;
         var now = new Date(). getTime(). toString();
         var data = JSON. parse( localStorage. getItem( 'myLsItem'));
             if( now > ( data[ 'myTime'] + ( 1 * hours))){
                 getFromAPI();
            }
             else {
                 getFromLS( data);
            }
    }

     // Get data from Local Storage
     function getFromLS(){
         var myItem = data. items[ 0]. volumeInfo. title;
         jQuery( navHooker). append( myItem);
         console. log( 'fetch from Local Storge..' + myItem);
    }

     // Get data from API
     function getFromAPI(){
         jQuery. ajax({
         url: url,
         dataType: 'jsonp',
         success : function( data) {
             var myItem = data. items[ 0]. volumeInfo. title;
             jQuery( navHooker). append( myItem);
                 // var time now, append it to the end of the data object and stringify so it can be stored in Local Storage
                 var appTime = new Date(). getTime();
                 data. myTime = appTime;
                 var jsonStore = JSON. stringify( data);
                 localStorage. setItem( 'myLsItem', jsonStore);
                 console. log( 'fetch from API..' + myItem );
         }
        });
    }

 and if you wanna try this, I used this example HTML

< div id= "myNavigation" >
< ul >
< li >Link 1 </ li >
< li >Link 2 </ li >
< li >Link 3 </ li >
</ ul >
</ div >