From 3c3c9a602650dff621acd323dafceec2b1d087b6 Mon Sep 17 00:00:00 2001 From: Sean Date: Thu, 20 Oct 2022 19:00:35 +0800 Subject: [PATCH] Added use local storage hook (#36) --- .../src/hooks/useLocalStorage/index.js | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 packages/bruno-app/src/hooks/useLocalStorage/index.js diff --git a/packages/bruno-app/src/hooks/useLocalStorage/index.js b/packages/bruno-app/src/hooks/useLocalStorage/index.js new file mode 100644 index 00000000..5a0fb347 --- /dev/null +++ b/packages/bruno-app/src/hooks/useLocalStorage/index.js @@ -0,0 +1,22 @@ +import { useState, useEffect } from 'react'; + +export default function useLocalStorage(key, defaultValue) { + const [value, setValue] = useState(() => { + try { + const saved = localStorage.getItem(key); + if (saved !== null) { + return JSON.parse(saved); + } + return defaultValue; + } catch { + return defaultValue; + } + }); + + useEffect(() => { + const rawValue = JSON.stringify(value); + localStorage.setItem(key, rawValue); + }, [key, value]); + + return [value, setValue]; +}