I successfully applied local storage in my component and would like to create my first hook, which will take care of the local storage, so I can re-use it in my other components.
/* EXAMPLE */
//useState:
const [state,setState] = useState("");
setValue("Hello"); // WORKS!
//useLocalHook:
const [hook_value,setHookValue] = useLocalStorage("");
setHookValue("New Value"); // NOT WORKING
I read guides about custom hooks, but they are not using the setFunction for their custom hooks, is this impossible to do?
Parent:
// Local storage
const [data,setData] = useLocalStorage("mydata","");
useEffect(()=>{
setData(new_value);
},[data]);
Hook:
const useLocalStorage = (storage_key,initial_value) => {
const [value,setValue] = useState(getLocalStorage(storage_key,initial_value));
/* LOCAL STORAGE */
function saveLocalStorage(key,value){
if (typeof window !== "undefined") {
// Set New Default Value
const saved_value = JSON.stringify(value);
console.log(`Key:${key} stored:${value}`);
localStorage.setItem(key,saved_value);
}
}
function getLocalStorage(key,initial_value)
{
if (typeof window !== "undefined") {
const value = JSON.parse(localStorage.getItem(key));
console.log(`Key:${key} received:${value}`);
if(value)
{
return value;
}
}
// Not found, return initial value
return initial_value;
}
function clearLocalStorage()
{
localStorage.clear();
}
function setValue(new_val)
{
value = new_val;
}
// Save settings in local storage
useEffect(()=>{
saveLocalStorage(storage_key,value);
},[value]);
// Return value
return [value];
}
What am I not understanding /& doing wrong if it's possible to change the value with custom hooks?
const [data, setData] = useLocalStorage("mydata",""), but in your hookuseLocalStorage, it's only returning an array with one elementreturn [value], which should bereturn [value, setValue]