From aeb8bb0d05c6978f0a30383a593e59858ffd7425 Mon Sep 17 00:00:00 2001 From: Frederik Bolding Date: Sat, 2 Sep 2023 23:08:07 +0200 Subject: [PATCH] Persist filters (#94) --- src/components/Filters.tsx | 4 ++-- src/context/SearchContext.tsx | 31 +++++++++++++++++++++++++++---- 2 files changed, 29 insertions(+), 6 deletions(-) diff --git a/src/components/Filters.tsx b/src/components/Filters.tsx index 6a8b7f291..e6af8ccbe 100644 --- a/src/components/Filters.tsx +++ b/src/components/Filters.tsx @@ -56,7 +56,7 @@ export const Filters = () => { @@ -71,7 +71,7 @@ export const Filters = () => { diff --git a/src/context/SearchContext.tsx b/src/context/SearchContext.tsx index 7f2ad702b..32e00af4a 100644 --- a/src/context/SearchContext.tsx +++ b/src/context/SearchContext.tsx @@ -1,11 +1,34 @@ -import React, { createContext, useState } from "react"; +import React, { createContext, useEffect, useState } from "react"; export const SearchContext = createContext({}); +const LOCALSTORAGE_KEY = "filters"; + export const SearchProvider = ({ children }) => { + const loadPersisted = () => { + try { + const result = window.localStorage.getItem(LOCALSTORAGE_KEY); + if (result) { + return JSON.parse(result); + } + } catch {} + return null; + }; + + const defaults = loadPersisted(); + const [query, setQuery] = useState(""); - const [showTestnets, setShowTestnets] = useState(false); - const [showDeprecated, setShowDeprecated] = useState(false); + const [showTestnets, setShowTestnets] = useState( + defaults?.showTestnets ?? false + ); + const [showDeprecated, setShowDeprecated] = useState( + defaults?.showDeprecated ?? false + ); + + useEffect(() => { + const str = JSON.stringify({ showTestnets, showDeprecated }); + window.localStorage.setItem(LOCALSTORAGE_KEY, str); + }, [showTestnets, showDeprecated]); return ( { showTestnets, setShowTestnets, showDeprecated, - setShowDeprecated + setShowDeprecated, }} > {children}