Advertisement
aldikhan13

Nextjs Custom LocalStorage Component

Jun 11th, 2021
1,768
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2. * Why you must be created custom component for locaStorage, because localStorage is not support in ssr, if you not created
  3. * custom component for localStorage, you  can get error response like localStorage is not defined.
  4. */
  5.  
  6. /**
  7. * Nextjs Components Territory
  8. */
  9. function Storage(props) {
  10.     const LocalStorage = ({ type, keys, value, onLocalStorage }) => {
  11.         switch (type) {
  12.             case 'set':
  13.                 keys !== undefined && window.localStorage.setItem(keys, value)
  14.                 break
  15.             case 'get':
  16.                 keys !== undefined && onLocalStorage(window.localStorage.getItem(keys))
  17.                 break
  18.             case 'remove':
  19.                 keys !== undefined && window.localStorage.removeItem(keys)
  20.                 break
  21.             case 'clear':
  22.                 keys !== undefined && window.localStorage.clear()
  23.                 break
  24.             default:
  25.                 alert('localStorage type undefined')
  26.                 break
  27.     }
  28. }
  29.  
  30.     return <div>{LocalStorage(props)}</div>
  31. }
  32.  
  33. export default Storage
  34.  
  35. /**
  36. * Nextjs Pages Teritory
  37. */
  38.  
  39. import dynamic from 'next/dynamic'
  40. const LocaStorage = dynamic(() => import('../components/Storage'), { ssr: false })
  41.  
  42. function Home() {
  43.     const getLocalStorage = (val) => alert(val)
  44.  
  45.     return (
  46.         <div>
  47.             <LocaStorage type={'set'} keys={'name'} value={'My name is restu wahyu saputra'} />
  48.             <LocaStorage type={'get'} keys={'name'} onLocalStorage={getLocalStorage} />
  49.         </div>
  50.     )
  51. }
  52.  
  53. export default Home
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement