useEffect(() => {
// setter
localStorage.setItem('myData', data);
// getter
localStorage.getItem('myData');
// remove
localStorage.removeItem('myData');
// remove all
localStorage.clear();
}, [])
/*
Next JS runs your code twice making using window impossible
So you can do this
*/
window?.localStorage?.whatever()
//local storage hook for SSR
import { useCallback, useEffect, useState } from "react";
export const useLocalStorage = (key, initialValue) => {
const initialize = (key) => {
try {
const item = localStorage.getItem(key);
if (item && item !== "undefined") {
return JSON.parse(item);
}
localStorage.setItem(key, JSON.stringify(initialValue));
return initialValue;
} catch {
return initialValue;
}
};
const [state, setState] = useState(null)
useEffect(()=>{
setState(initialize(key));
},[]);
const setValue = useCallback(
(value) => {
try {
const valueToStore = value instanceof Function ? value(storedValue) : value;
setState(valueToStore);
localStorage.setItem(key, JSON.stringify(valueToStore));
} catch (error) {
console.log(error);
}
},
[key, setState]
);
const remove = useCallback(() => {
try {
localStorage.removeItem(key);
} catch {
console.log(error);
}
}, [key]);
return [state, setValue, remove];
};
// src:
// https://stackoverflow.com/questions/68808837/next-js-use-localstorage-problem-with-ssr
import { FunctionComponent, createElement, useState, MouseEvent, useEffect } from 'react'
interface Props {
type: string
}
const CleanupLocalStorage: FunctionComponent<Props> = (props: Props) => {
const LocalStorage = ({ type }): void => {
switch (type) {
case 'clear':
type !== undefined && window.localStorage.clear()
break
default:
alert('localStorage type undefined')
break
}
}
useEffect(() => {
LocalStorage(props)
},[])
return <></>
}
export default CleanupLocalStorage