Skip to content

Commit

Permalink
fix(code-block): fix local-storage breakage (#735)
Browse files Browse the repository at this point in the history
* fix(code-block): check before accessing local storage

* chore(code-block): add changeset
  • Loading branch information
zchsh committed Oct 3, 2022
1 parent eff7596 commit 0aa2389
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/shaggy-readers-brake.md
@@ -0,0 +1,5 @@
---
'@hashicorp/react-code-block': patch
---

Fixes an issue where code-block would throw an error and potentially break the consuming app if local storage is disabled.
5 changes: 3 additions & 2 deletions packages/code-block/provider/index.tsx
@@ -1,4 +1,5 @@
import { createContext, useState, useContext, useEffect, useMemo } from 'react'
import safeLocalStorage from '../utils/safe-local-storage'

export function useTabGroups() {
return useContext(CodeTabsContext)
Expand Down Expand Up @@ -42,13 +43,13 @@ export default function CodeTabsProvider({ children }) {
// then save it to local storage
if (updatedPreferences.length > 0) {
const storedValueJson = JSON.stringify(updatedPreferences)
window.localStorage.setItem(LOCAL_STORAGE_KEY, storedValueJson)
safeLocalStorage.setItem(LOCAL_STORAGE_KEY, storedValueJson)
}
}, [activeTabGroup])

// Load activeTabGroup from cookie, if available
useEffect(() => {
const maybeStoredValue = window.localStorage.getItem(LOCAL_STORAGE_KEY)
const maybeStoredValue = safeLocalStorage.getItem(LOCAL_STORAGE_KEY)
if (maybeStoredValue) {
// Try / catch in case JSON.parse fails
try {
Expand Down
40 changes: 40 additions & 0 deletions packages/code-block/utils/safe-local-storage.ts
@@ -0,0 +1,40 @@
/**
* Returns `true` if window.localStorage can be used,
* or `false` otherwise.
*
* Based on:
* https://github.com/Modernizr/Modernizr/blob/master/feature-detects/storage/localstorage.js
*/
function isLocalStorageAvailable() {
const test = 'test'
try {
window.localStorage.setItem(test, test)
window.localStorage.getItem(test)
window.localStorage.removeItem(test)
return true
} catch (e) {
return false
}
}

/**
* Gets an item from local storage, if available.
* Safely returns `null` if local storage is unavailable.
*/
function getItem(key: string) {
if (!isLocalStorageAvailable()) return null
return window.localStorage.getItem(key)
}

/**
* Sets an item in local storage.
* Safely returns `null` if local storage is unavailable.
*/
function setItem(key: string, value: string) {
if (!isLocalStorageAvailable()) return null
return window.localStorage.setItem(key, value)
}

const safeLocalStorage = { getItem, setItem }

export default safeLocalStorage

1 comment on commit 0aa2389

@vercel
Copy link

@vercel vercel bot commented on 0aa2389 Oct 3, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.