main
Last change
on this file since 5d6f37a was 5d6f37a, checked in by Naum Shapkarovski <naumshapkarovski@…>, 7 weeks ago |
add customer
|
-
Property mode
set to
100644
|
File size:
1.7 KB
|
Rev | Line | |
---|
[5d6f37a] | 1 | import { useEffect, useState, useCallback } from 'react';
|
---|
| 2 |
|
---|
| 3 | // ----------------------------------------------------------------------
|
---|
| 4 |
|
---|
| 5 | export function useLocalStorage(key: string, initialState: any) {
|
---|
| 6 | const [state, setState] = useState(initialState);
|
---|
| 7 |
|
---|
| 8 | useEffect(() => {
|
---|
| 9 | const restored = getStorage(key);
|
---|
| 10 |
|
---|
| 11 | if (restored) {
|
---|
| 12 | setState((prevValue: any) => ({
|
---|
| 13 | ...prevValue,
|
---|
| 14 | ...restored,
|
---|
| 15 | }));
|
---|
| 16 | }
|
---|
| 17 | }, [key]);
|
---|
| 18 |
|
---|
| 19 | const updateState = useCallback(
|
---|
| 20 | (updateValue: any) => {
|
---|
| 21 | setState((prevValue: any) => {
|
---|
| 22 | setStorage(key, {
|
---|
| 23 | ...prevValue,
|
---|
| 24 | ...updateValue,
|
---|
| 25 | });
|
---|
| 26 |
|
---|
| 27 | return {
|
---|
| 28 | ...prevValue,
|
---|
| 29 | ...updateValue,
|
---|
| 30 | };
|
---|
| 31 | });
|
---|
| 32 | },
|
---|
| 33 | [key]
|
---|
| 34 | );
|
---|
| 35 |
|
---|
| 36 | const update = useCallback(
|
---|
| 37 | (name: string, updateValue: any) => {
|
---|
| 38 | updateState({
|
---|
| 39 | [name]: updateValue,
|
---|
| 40 | });
|
---|
| 41 | },
|
---|
| 42 | [updateState]
|
---|
| 43 | );
|
---|
| 44 |
|
---|
| 45 | const reset = useCallback(() => {
|
---|
| 46 | removeStorage(key);
|
---|
| 47 | setState(initialState);
|
---|
| 48 | }, [initialState, key]);
|
---|
| 49 |
|
---|
| 50 | return {
|
---|
| 51 | state,
|
---|
| 52 | update,
|
---|
| 53 | reset,
|
---|
| 54 | };
|
---|
| 55 | }
|
---|
| 56 |
|
---|
| 57 | // ----------------------------------------------------------------------
|
---|
| 58 |
|
---|
| 59 | export const getStorage = (key: string) => {
|
---|
| 60 | let value = null;
|
---|
| 61 |
|
---|
| 62 | try {
|
---|
| 63 | const result = window.localStorage.getItem(key);
|
---|
| 64 |
|
---|
| 65 | if (result) {
|
---|
| 66 | value = JSON.parse(result);
|
---|
| 67 | }
|
---|
| 68 | } catch (error) {
|
---|
| 69 | console.error(error);
|
---|
| 70 | }
|
---|
| 71 |
|
---|
| 72 | return value;
|
---|
| 73 | };
|
---|
| 74 |
|
---|
| 75 | export const setStorage = (key: string, value: any) => {
|
---|
| 76 | try {
|
---|
| 77 | window.localStorage.setItem(key, JSON.stringify(value));
|
---|
| 78 | } catch (error) {
|
---|
| 79 | console.error(error);
|
---|
| 80 | }
|
---|
| 81 | };
|
---|
| 82 |
|
---|
| 83 | export const removeStorage = (key: string) => {
|
---|
| 84 | try {
|
---|
| 85 | window.localStorage.removeItem(key);
|
---|
| 86 | } catch (error) {
|
---|
| 87 | console.error(error);
|
---|
| 88 | }
|
---|
| 89 | };
|
---|
Note:
See
TracBrowser
for help on using the repository browser.