-
-
Save fedek6/fd494ee3d33e79d0a3968d4741e646d7 to your computer and use it in GitHub Desktop.
/* eslint-disable no-console */ | |
/* eslint-disable react-hooks/exhaustive-deps */ | |
import { useState, useEffect } from "react"; | |
export const useLocalStorage = <T>(key: string, initialValue: T) => { | |
const [storedValue, setStoredValue] = useState<T | undefined>(); | |
const setValue = (value: T) => { | |
window.localStorage.setItem(key, JSON.stringify(value)); | |
}; | |
useEffect(() => { | |
const value = window.localStorage.getItem(key); | |
if (value) { | |
try { | |
const parsed = JSON.parse(value) as T; | |
setStoredValue(parsed); | |
} catch (error) { | |
console.log(error); | |
setStoredValue(initialValue); | |
} | |
} else { | |
setStoredValue(initialValue); | |
} | |
}, []); | |
useEffect(() => { | |
if (storedValue) { | |
setValue(storedValue); | |
} | |
}, [storedValue]); | |
return [storedValue as T, setStoredValue] as const; | |
}; |
thanks broooo
thanks bro
genioooooooo obrigado irmao
pra quem ficar com duvida usa assim. const [paragraphs, setParagraphs] = useLocalStorage('keyvalue', [])
Finally a working solution. Thanks. Can you please explain why the code doesn't throw an error (the window object is not defined) during the build process? I tried to implement a solution but I ended up getting this error.
import { useState, useEffect } from "react";
export const useLocalStorage = <T,>(key: string, initialValue: T) => {
const [storedValue, setStoredValue] = useState(() => {
if (typeof window === "undefined") {
return initialValue;
}
try {
// Get from local storage by key
const item = window.localStorage.getItem(key);
// Parse stored json or if none return initialValue
return item ? JSON.parse(item) : initialValue;
} catch (error) {
// If error also return initialValue
console.log(error);
return initialValue;
}
});
useEffect(() => {
const setValue = (value: T) => {
window.localStorage.setItem(key, JSON.stringify(value));
};
if (storedValue) {
setValue(storedValue);
}
}, [storedValue, key]);
return [storedValue, setStoredValue];
};
Implimentation useLocalSTorage in NextJS
I'm getting this warning in chrome, when using the value for a text input value:
Warning: A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components
Any idea how to prevent this?
thanks bro
thanks bro.