Created
July 25, 2019 07:10
-
-
Save joshuacerbito/c9ff5a4ba2594127c356afa6aee761ae to your computer and use it in GitHub Desktop.
Custom React Hook for handling session storage
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState } from 'react'; | |
export default function useSessionStorage(key, initialValue) { | |
const [item, setInnerValue] = useState(() => { | |
try { | |
return window.sessionStorage.getItem(key) | |
? JSON.parse(window.sessionStorage.getItem(key)) | |
: initialValue; | |
} catch (error) { | |
return initialValue; | |
} | |
}); | |
const setValue = value => { | |
try { | |
setInnerValue(value); | |
window.sessionStorage.setItem(key, JSON.stringify(value)); | |
} catch (e) { | |
console.log(e); | |
} | |
}; | |
return [item, setValue]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What about retrieving strings from the sessionStorage?