-1

I am new to localstorage.I am trying to store json data in one file and retrieving the data in other file.Below is my json data which i have fetched from an url.I have tried storing feeds data using using localstorage now i am tring to fetch the data in other html file.But i am getting only the final object from the feeds.How can i get all the feed objects in other file.

{
  "channel":{
     "id":9,
     "name":"my_house", 
     "description":"Netduino Plus connected to sensors around the house",
     "latitude":"40.44",                                                         
     "longitude":"-79.9965",
     "field1":"Light", 
     "field2":"Outside Temperature", 
     "created_at":"2010-12-14T01:20:06Z",
     "updated_at":"2017-02-13T09:09:31Z",
     "last_entry_id":11664376
},
     "feeds":[{
        "created_at":"2017-02-13T09:07:16Z",    
        "entry_id":11664367,
        "field1":"196",
        "field2":"31.507430997876856"
     },{
        "created_at":"2017-02-13T09:07:31Z",  
        "entry_id":11664368,
        "field1":"192",
        "field2":"30.743099787685775"
     },{
        "created_at":"2017-02-13T09:07:46Z",     
        "entry_id":11664369,
        "field1":"208",
        "field2":"28.280254777070063" 
    }]}

One.html:-(here i am storing all the feeds data)

 $.ajax({
        url : "https://api.thingspeak.com/channels/9/feeds.json?results=3",
        dataType:"json",
        cache: false,
        error:function (xhr, ajaxOptions, thrownError){
        debugger;
        alert(xhr.statusText);
        alert(thrownError);
    },
        success : function(json1) {
        console.log(json1);

        json1.feeds.forEach(function(feed, i) {
        console.log("\n The deails of " + i + "th Object are :          \nCreated_at: " + feed.created_at + "\nEntry_id:" + feed.entry_id + "\nField1:" + feed.field1 + "\nField2:" + feed.field2); 
        localStorage.setItem('Created_at', feed.created_at);
        var create = localStorage.getItem('Created_at');
        console.log(create);
        localStorage.setItem('Entry_id', feed.entry_id);
        var entry = localStorage.getItem('Entry_id');
        console.log(entry);
        localStorage.setItem('Field1', feed.field1);
        var fd1 = localStorage.getItem('Field1');
        console.log(fd1);
        localStorage.setItem('Field2', feed.field2);
        var fd2 = localStorage.getItem('Field2');
        console.log(fd2);
   });

other.html:(here i am trying to fetch the localstorage data)

<script>

            // Called on body's `onload` event
            function init() {
                // Retrieving the text input's value which was stored into localStorage

                var create = localStorage.getItem('Created_at');
                console.log(create);
                document.writeln("<br>Created_at  = "+create);
                var entry = localStorage.getItem('Entry_id');
                document.writeln("<br>Entry_id  = "+entry);
                var fd1 = localStorage.getItem('Field1');
                document.writeln("<br>Field1  = "+fd1);
                var fd2 = localStorage.getItem('Field2');
                document.writeln("<br>Field2  = "+fd2);

            }
    </script>
Anusha
  • 239
  • 1
  • 3
  • 12

2 Answers2

0

Because you are over-riding the localStorage item in your for Loop.

The required for loop when simplified looks like:

 json1.feeds.forEach(function(feed, i) {
    localStorage.setItem('Created_at', feed.created_at); //Gets over-riden on every iteration
    localStorage.setItem('Field1', feed.field1);});

That's why after the loop is completed. The Created_at field would only have the value of the most recently processed item in the array i.e. the last element. What you need to is create a corresponding array where each element would correspond to a feed item that you are reading from the API response.

Now, localStorage can simply store key value pairs. It doesn't have support for types like array. What you can do is something on these lines (Untested Code):

 json1.feeds.forEach(function(feed, i) {
     var feedsArray = JSON.parse(localStorage.getItem('feedsArray'));
     feedsArray.push(feed);
     localStorage.setItem('feedsArray',JSON.stringify(feedsArray));

});

Yes, You will have to check if feedsArray key exists or not and set it as an empty array the first time. I have deliberately not put in the entire code as it is quite simple and should be good exercise for you.

So, once you are done and you want to read all the feeds from localStorage. Just get the feedsArray key and parse it and then iterate over it. Put simply, the basic idea is to have a JSON array of feeds and store it as a string with key feedsArray in localStorage.

The code snippet I have given above can get you started toward the solution I propose.

Relevant SO Post

Community
  • 1
  • 1
Vivek Pradhan
  • 4,777
  • 3
  • 26
  • 46
  • I have tried as you told but again i am just retrieving only 1 object .The code is below which i have tried.Can you please help me where i am doing wrong.Thankyou@Vivek Pradhan. New.html: var feedsArray = []; feedsArray.push(feed); localStorage.setItem('feedsArray',JSON.stringify(feedsArray)); new2.html:var feedsArray = []; var create =JSON.parse(localStorage.getItem('feedsArray')); console.log(create); – Anusha Feb 14 '17 at 04:33
  • @Anusha. Again you are creating the `feedsArray` and setting `var feedsArray = []; ` inside the `for` loop. That is why. It won't work. You need to define the array outside the for loop and set it on localStorage. Then, inside the `for` loop you need to do `var savedArr = JSON.parse(localStorage.getItem('feedsArray'));`. Then push the feed items into `savedArr` array and then again update it in localStorage – Vivek Pradhan Feb 14 '17 at 08:56
0

The answer for the above issue is below.through which i got the solution.But not too sure if der is any wrong. one.html:

 $.ajax({
    url : "https://api.thingspeak.com/channels/9/feeds.json?results=3",
    dataType:"json",
    cache: false,
    error:function (xhr, ajaxOptions, thrownError){
    debugger;
    alert(xhr.statusText);
    alert(thrownError);
},
    success : function(json1) {
    console.log(json1);

    json1.feeds.forEach(function(feed, i) {
    console.log("\n The deails of " + i + "th Object are :\nCreated_at: " + feed.created_at + "\nEntry_id:" + feed.entry_id + "\nField1:" + feed.field1 + "\nField2:" + feed.field2); 
    var feedsArray = JSON.parse(localStorage.getItem('feedsArray'));
    feedsArray.push(feed);
    localStorage.setItem('feedsArray',JSON.stringify(feedsArray));
    for (var i = 0; i < localStorage.length;i++){
        var savedArr =localStorage.getItem('feedsArray[i]')                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  
    }
  });

other.html:

        // Called on body's `onload` event
        function init() {
            // Retrieving the text input's value which was stored into localStorage

            var feedsArray = JSON.parse(localStorage.getItem('feedsArray'));
                    for (var i = 0; i < localStorage.length;i++){
                        var savedArr =localStorage.getItem('feedsArray[i]');
                        //feedsArray.push(savedArr);
                    }
                    console.log(savedArr);
                        document.writeln("<br>FEEDS  = "+savedArr);

        }
</script
Anusha
  • 239
  • 1
  • 3
  • 12