Search code examples
javascriptbrowsersafarilocal-storageopera

localStorage code working perfectly in Opera, but only half in Safari


I have been coding my PWA for about a week now and I need some help finding out why the code works completely in Opera, but not in Safari.

How to replicate my issue:

  1. Open my project (link) in both Safari (on mac or iphone or whatever) and Opera (or chrome or whatever)
  2. Click the 3rd button from the left and make a meal (make some random stuff up)
  3. Once you have made the meal, then notice the toggle switch and switch it on.
  4. Reload the page and see that the meal still shows but the toggle doesn't show for safari.
  5. It doesn't work in Safari for some reason

Am I using code that shouldn't be allowed in Safari or something? How do I work around this?

I have deployed a link as well to the site via firebase here


Solution

  • After some debugging on discord, we found that in script.js, these lines were causing the issue:

    if (mealTargetted) {
          userData.mealInformation.find(a => a.name == e.target.parentNode.parentNode.innerText).addedToShoppingList = false;
          localStorage.setItem('data', JSON.stringify(userData));
    } else {
          userData.mealInformation.find(a => a.name == e.target.parentNode.parentNode.innerText).addedToShoppingList = true;
          localStorage.setItem('data', JSON.stringify(userData));
    }
    

    Github

    Error

    What was happening was that somehow, in safari, e.target.parentNode.parentNode.innerText had a trailing space compared to the saved localStorage result: As you can see, e.innerText has a trailing space

    console.log(userData.mealInformation, e.target.parentNode.parentNode.innerText)

    This meant that a.name == e.target.parentNode.parentNode.innerText.trim() was never satisfied, and so userData.mealInformation.find(a => a.name == e.target.parentNode.parentNode.innerText) returns undefined, throwing an undefined is not an object error, causing the toggle to appear not to change.

    Solution

    What this means was that we had to trim e.target.parentNode.parentNode.innerText:

    if (mealTargetted) {
          userData.mealInformation.find(a => a.name == e.target.parentNode.parentNode.innerText.trim()).addedToShoppingList = false;
          localStorage.setItem('data', JSON.stringify(userData));
    } else {
          userData.mealInformation.find(a => a.name == e.target.parentNode.parentNode.innerText.trim()).addedToShoppingList = true;
          localStorage.setItem('data', JSON.stringify(userData));
    }
    

    So this wasn't a localStorage issue, just a code issue