aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--src/hooks/useLocalStorage.ts30
-rw-r--r--src/index.tsx3
-rw-r--r--src/react-app-env.d.ts1
3 files changed, 33 insertions, 1 deletions
diff --git a/src/hooks/useLocalStorage.ts b/src/hooks/useLocalStorage.ts
new file mode 100644
index 0000000..5893317
--- /dev/null
+++ b/src/hooks/useLocalStorage.ts
@@ -0,0 +1,30 @@
+import { useState, useCallback } from 'react';
+
+function useLocalStorage<T>(key: string, initialValue: T): [T, (value: T) => void] {
+ const [storedValue, setStoredValue] = useState<T>(() => {
+ try {
+ const item = window.localStorage.getItem(key);
+ return item ? JSON.parse(item) : initialValue;
+ } catch (error) {
+ console.log(error);
+ return initialValue;
+ }
+ });
+
+ const setValue = useCallback((value: T) => {
+ setStoredValue((originalValue: T) => {
+ try {
+ const valueToStore = value instanceof Function ? value(originalValue) : value;
+ window.localStorage.setItem(key, JSON.stringify(valueToStore));
+ return valueToStore;
+ } catch (error) {
+ console.log(error);
+ }
+ });
+ }, [key]);
+
+ return [storedValue, setValue];
+}
+
+export default useLocalStorage;
+
diff --git a/src/index.tsx b/src/index.tsx
index 30d0f07..c6cab71 100644
--- a/src/index.tsx
+++ b/src/index.tsx
@@ -3,6 +3,7 @@ import ReactDOM from 'react-dom';
import './style.css';
import './fonts/Bitter-Regular.woff';
+import useLocalStorage from './hooks/useLocalStorage';
import Timer from './components/Timer';
interface Solution {
@@ -12,7 +13,7 @@ interface Solution {
const App: React.FC = () => {
const [author, setAuthor] = useState<string>('anonymous');
- const [solutions, setSolutions] = useState<Solution[]>([]);
+ const [solutions, setSolutions] = useLocalStorage<Solution[]>('solutions', []);
const registerResult = (result: string) => {
setSolutions([{ author, result }, ...solutions]);
diff --git a/src/react-app-env.d.ts b/src/react-app-env.d.ts
new file mode 100644
index 0000000..6431bc5
--- /dev/null
+++ b/src/react-app-env.d.ts
@@ -0,0 +1 @@
+/// <reference types="react-scripts" />