Skip to content

Commit

Permalink
fix(styled-components): local storage not available (#129)
Browse files Browse the repository at this point in the history
Co-authored-by: Stefen Alper <stefen.alper@gmail.com>
  • Loading branch information
salper and salper committed Aug 10, 2020
1 parent e57ca07 commit 304602c
Showing 1 changed file with 24 additions and 8 deletions.
32 changes: 24 additions & 8 deletions packages/core/src/colorModes.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,30 @@ import {

const STORAGE_KEY = 'xstyled-color-mode'

const storage = {
get: () =>
typeof window === 'undefined'
? null
: window.localStorage.getItem(STORAGE_KEY),
set: (value) => window.localStorage.setItem(STORAGE_KEY, value),
clear: () => window.localStorage.removeItem(STORAGE_KEY),
}
const isLocalStorageAvailable =
typeof window !== 'undefined' &&
(() => {
try {
const STORAGE_TEST_KEY = `${STORAGE_KEY}-test`
window.localStorage.setItem(STORAGE_TEST_KEY, STORAGE_TEST_KEY)
window.localStorage.removeItem(STORAGE_TEST_KEY)
return true
} catch (err) {
return false
}
})()

const storage = isLocalStorageAvailable
? {
get: () => window.localStorage.getItem(STORAGE_KEY),
set: (value) => window.localStorage.setItem(STORAGE_KEY, value),
clear: () => window.localStorage.removeItem(STORAGE_KEY),
}
: {
get: () => null,
set: () => {},
clear: () => {},
}

const COLOR_MODE_CLASS_PREFIX = 'xstyled-color-mode-'
const getColorModeClassName = (mode) => `${COLOR_MODE_CLASS_PREFIX}${mode}`
Expand Down

0 comments on commit 304602c

Please sign in to comment.