mirror of
https://github.com/cheveguerra/whaticket-community.git
synced 2026-04-19 04:09:26 +00:00
improvement: moved user data from localstorage to context
This commit is contained in:
29
frontend/src/hooks/useLocalStorage/index.js
Normal file
29
frontend/src/hooks/useLocalStorage/index.js
Normal file
@@ -0,0 +1,29 @@
|
||||
import { useState } from "react";
|
||||
import toastError from "../../errors/toastError";
|
||||
|
||||
export function useLocalStorage(key, initialValue) {
|
||||
const [storedValue, setStoredValue] = useState(() => {
|
||||
try {
|
||||
const item = localStorage.getItem(key);
|
||||
return item ? JSON.parse(item) : initialValue;
|
||||
} catch (error) {
|
||||
toastError(error);
|
||||
return initialValue;
|
||||
}
|
||||
});
|
||||
|
||||
const setValue = value => {
|
||||
try {
|
||||
const valueToStore =
|
||||
value instanceof Function ? value(storedValue) : value;
|
||||
|
||||
setStoredValue(valueToStore);
|
||||
|
||||
localStorage.setItem(key, JSON.stringify(valueToStore));
|
||||
} catch (error) {
|
||||
toastError(error);
|
||||
}
|
||||
};
|
||||
|
||||
return [storedValue, setValue];
|
||||
}
|
||||
Reference in New Issue
Block a user