From d8485252db3de18bca83147bf4ed70b0f42d49ac Mon Sep 17 00:00:00 2001 From: zainbinfurqan Date: Fri, 2 Oct 2020 17:07:37 +0500 Subject: [PATCH 1/3] create counter custom hook --- hooks/useLocalStorageState.js | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 hooks/useLocalStorageState.js diff --git a/hooks/useLocalStorageState.js b/hooks/useLocalStorageState.js new file mode 100644 index 0000000..22c6b0e --- /dev/null +++ b/hooks/useLocalStorageState.js @@ -0,0 +1,27 @@ +import React, { useEffect, useState } from 'react'; + +function useLocalStorageState(key, defaultVa1ue) { + const [state, setState] = useState(() => { + let value; + try { + value = JSON.parse(window.localStorage.getItem(key) || String(defaultVa1ue)) + } + catch (e) { + value = defaultVa1ue; + } + return value; + }) + useEffect( + () => { + window.localStorage.setItem(key, state); + }, [state]); + return [state, setState]; +} +export default function Counter() { + const [count, setcount] = useLocalStorageState("my-app-count", 0) + return ( +
+ +
+ ) +} \ No newline at end of file From a8159bde7d61d6a479d81c586af2e2a764e34532 Mon Sep 17 00:00:00 2001 From: zainbinfurqan Date: Sat, 3 Oct 2020 03:37:39 +0500 Subject: [PATCH 2/3] update code --- hooks/useLocalStorageState.js | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/hooks/useLocalStorageState.js b/hooks/useLocalStorageState.js index 22c6b0e..6e2bb46 100644 --- a/hooks/useLocalStorageState.js +++ b/hooks/useLocalStorageState.js @@ -1,6 +1,6 @@ import React, { useEffect, useState } from 'react'; -function useLocalStorageState(key, defaultVa1ue) { +export default function useLocalStorageState(key, defaultVa1ue) { const [state, setState] = useState(() => { let value; try { @@ -17,11 +17,11 @@ function useLocalStorageState(key, defaultVa1ue) { }, [state]); return [state, setState]; } -export default function Counter() { - const [count, setcount] = useLocalStorageState("my-app-count", 0) - return ( -
- -
- ) -} \ No newline at end of file +// export default function Counter() { +// const [count, setcount] = useLocalStorageState("my-app-count", 0) +// return ( +//
+// +//
+// ) +// } \ No newline at end of file From df2afdb6ba3379154d309847ac2933ea1c06948c Mon Sep 17 00:00:00 2001 From: zainbinfurqan Date: Sat, 3 Oct 2020 03:39:51 +0500 Subject: [PATCH 3/3] update code with export default hook --- hooks/useLocalStorageState.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/hooks/useLocalStorageState.js b/hooks/useLocalStorageState.js index 6e2bb46..e147840 100644 --- a/hooks/useLocalStorageState.js +++ b/hooks/useLocalStorageState.js @@ -1,4 +1,4 @@ -import React, { useEffect, useState } from 'react'; +import { useEffect, useState } from 'react'; export default function useLocalStorageState(key, defaultVa1ue) { const [state, setState] = useState(() => {