Skip to content

Commit

Permalink
fix: ignore unexpected values in localStorage (#146)
Browse files Browse the repository at this point in the history
  • Loading branch information
wKovacs64 authored Feb 13, 2023
1 parent ca740c1 commit a6b609d
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 8 deletions.
5 changes: 5 additions & 0 deletions .changeset/neat-colts-impress.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'gatsby-plugin-use-dark-mode': patch
---

Ignore unexpected values in localStorage.
13 changes: 5 additions & 8 deletions src/gatsby-node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,19 +86,16 @@ function generateNoFlashScript({
var preferDarkQuery = '(prefers-color-scheme: dark)';
var mql = window.matchMedia(preferDarkQuery);
var supportsColorSchemeQuery = mql.media === preferDarkQuery;
var localStorageTheme = null;
var localStorageValue = null;
try {
localStorageTheme = localStorage.getItem(storageKey);
localStorageValue = JSON.parse(localStorage.getItem(storageKey));
} catch (err) {}
var localStorageExists = localStorageTheme !== null;
if (localStorageExists) {
localStorageTheme = JSON.parse(localStorageTheme);
}
var isLocalStorageValueValid = localStorageValue === true || localStorageValue === false;
// Determine the source of truth
if (localStorageExists) {
if (isLocalStorageValueValid) {
// source of truth from localStorage
setClassOnDocumentBody(localStorageTheme);
setClassOnDocumentBody(localStorageValue);
} else if (supportsColorSchemeQuery) {
// source of truth from system
setClassOnDocumentBody(mql.matches);
Expand Down

0 comments on commit a6b609d

Please sign in to comment.