0

I have a massive problem, with little time to resolve it. I am creating my first mobile app for property search as a university project (its not based on real properties) I tried using different keys it does not work, Im not getting the basics. Basically I have a Jquery mobile app with many external pages which have details for a property, these pages have the same id but on different documents, When a user clicks the button to save, I want the title and the url of the page to be saved in local storage and to be retrieved by a third page called my favorites. The problem I am having is that when I go on each page and click save, it overrides what was already in local storage and it seems like each page has its own storage and as a result my favorites page always has only one favorite (the latest one), rather than a favorite list appending every time I click save. Here is my code:

<div data-role="header" id="samplePlacePage_hd">
    <h4 id="hutRef">add#redHut456</h4>
</div>

<div data-role="main" id="samplePlacePage_cont">

    <div id="image">
        <a href="#"><img src="images/redhut.jpeg" height="200px" width="100%" alt="Hut"></a>
    </div>

    <div id="place_title">
        <p id="hutHeading">Stunning Red Hut in Central Red Beach</p>
    </div>
    <div>
        <h4 style="float: left;">Rent: $2950pw</h4>
        <h4 style="float: right;">Deposit: 5500</h4>
    </div>

(Same code on both pages) This was the function I had in my script file:

$(document).on("pagecreate",function (argument) {

var favoritesPlaces = [];
var heading = document.getElementById('hutHeading').innerText;
var ref = document.getElementById('hutRef').innerText;
var refLink = ref.replace("add#","");

document.getElementById('hutFav').onclick = function () {
    var newFav = {
        title: heading,
        link: refLink
    };
    favoritesPlaces.push(newFav);
    console.log(favoritesPlaces);
    localStorage.setItem("favorites",JSON.stringify(favoritesPlaces));
}

})

Please help

Thanks

Ptmp727
  • 27
  • 6
  • Put that code in the post not a comment – zer00ne Jan 08 '18 at 00:25
  • Are you saying that you want persistent local memory shared accross multiple pages. Achieved with Javascript? – pastaleg Jan 08 '18 at 00:26
  • If you use the same key it will be overwritten. You need to have different keys for each page that you want settings to persist. – zer00ne Jan 08 '18 at 00:27
  • Yes Magnus, that Is what I want, – Ptmp727 Jan 08 '18 at 00:38
  • Then your question has already been asked before here https://stackoverflow.com/questions/29986657/persist-variables-between-page-loads . See the detailed answer there on why it cant be done and how you can proceed. – pastaleg Jan 08 '18 at 00:40
  • Possible duplicate of [Persist variables between page loads](https://stackoverflow.com/questions/29986657/persist-variables-between-page-loads) – pastaleg Jan 08 '18 at 00:41
  • Sorry new at this, not very good at posting the code properly, I have two pages with the same ID. Both are linked to one script file with that function, when I go to page 1 and click the button, it saves page1, if I click page1 ten times it appends the array 10 times, then if I go to page2 and click the button once, the previous 10 disappear and the page2 starts the array all over again from [0], if I need different keys then I have to repeat the code? – Ptmp727 Jan 08 '18 at 00:44
  • Sorry I am a bit retarded at this, Im not sure if its the same thing, but I get the point, If I need different keys, then i guess I am going to have to repeat my code. – Ptmp727 Jan 08 '18 at 00:52
  • All I want to do is save the title and the url of a page to local storage, I dont know how to put all my code in that grey box like other people, so that I can show properly what Im trying to do – Ptmp727 Jan 08 '18 at 00:53
  • @PeshotanPavri please stop using comments to post code. Edit the question to show what you have tried, what you expected and what you got, using proper markdown formatting for code. You can help yourself to get good answers by helping us see where you may be going wrong. – traktor Jan 08 '18 at 01:19
  • Yes I understand, first time posting on this, I have Done it now – Ptmp727 Jan 08 '18 at 01:55
  • Im starting to think maybe its because of: var favoritesPlaces = []; Is it because the array is empty each time the page is created? – Ptmp727 Jan 08 '18 at 02:01
  • Sorted!!!!! Thank you so much traktor53 – Ptmp727 Jan 08 '18 at 12:24

1 Answers1

1

Two additional considerations for you: checking the favorite has not been added already, and allowing the user to have multiple tabs open on pages from your site - adding one page as a favorite should not interfere with adding a different page as a favorite. And not to forget, if the local storage item does not exist create a new one :)

Basically I suggest retrieving local storage, checking for duplicates, updating and saving back to local storage all occur in a single click handler, E.G. by rearranging your code and adding a few lines:

$(document).on("pagecreate",function () {
    document.getElementById('hutFav').onclick = function () {

        var favoritesPlaces = localStorage.getItem("favorites");
        var heading = document.getElementById('hutHeading').innerText;
        var ref = document.getElementById('hutRef').innerText;
        var refLink = ref.replace("add#","");
        var newFav = {
            title: heading,
            link: refLink
        };

        favoritesPlaces = favoritesPlaces || '[]';    // string
        favoritesPlaces = JSON.parse(favoritesPlaces); // array
        if( !favoritesPlaces.some( fave => fave.link === refLink)) {
            favoritesPlaces.push( newFav)
            console.log(favoritesPlaces);
            localStorage.setItem("favorites",JSON.stringify(favoritesPlaces));
        }
        else {
           console.log("already a favorite");
        }
    }
})

(tested)

Note that clearing localStorage on any page clears it for all pages across a site. Once cleared, its cleared on all pages, there are no more favorites, and any page can be added again without being a duplicate. If a "remove this page from favorites" button is needed, a new function needs to be written to do it.

traktor
  • 17,588
  • 4
  • 32
  • 53
  • Hey That is incredible, I did figure out that i was declaring an empty array to start with, was a problem, but your code is so much cleaner, im going to test now :), thank you :) – Ptmp727 Jan 08 '18 at 03:59
  • Just not very familiar with the some() thing and the =>, trying to understand it and test it, Thanks – Ptmp727 Jan 08 '18 at 04:24
  • `=>` is part of the syntax of an [arrow function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions). They are not supported in all browsers so it may be wiser to not use them in JQuery. Try writing your own test to check if the favorite exists already and do nothing if it does. Good luck. – traktor Jan 08 '18 at 05:16
  • I tested the code, it works fine, except for the fact that the duplicates only work for the first property, the second time around, it does not prevent me from entering duplicates – Ptmp727 Jan 08 '18 at 05:18
  • Did you check for errors on the console? One of the `favoritesPlaces` was missing an `s` on the end ( now fixed in the answer). – traktor Jan 08 '18 at 05:51
  • Hi, thank you so much for taking the trouble, yes i checked that earlier, its not that, its a distinct pattern, when I erase my local storage and start the test all over, when I click the first property page it works perfectly, then if I go to another property page, it still works fine, except for it does not stop duplicate entries. – Ptmp727 Jan 08 '18 at 06:14
  • Only got a couple of hours left, .some() does not loop through the whole array of favoritesPlaces, only takes the first element, any help from anyone would be mych appreciated, thanks in advance – Ptmp727 Jan 08 '18 at 10:25
  • You are welcome. _If_ it was this answer that solved the issue for you, please [consider accepting it](https://meta.stackexchange.com/a/5235) – traktor Jan 15 '18 at 22:46
  • Done! Sorry about the delay – Ptmp727 Jan 22 '18 at 10:00