From e0fa161183f9e20c596ab7f91f26a804a0e3e3fb Mon Sep 17 00:00:00 2001 From: MURAGEH Date: Mon, 6 Feb 2023 20:18:32 +0300 Subject: [PATCH] add option to choose storage either localStorage and sessionStorage --- src/hooks/saveProgress/useSaveProgress.ts | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/hooks/saveProgress/useSaveProgress.ts b/src/hooks/saveProgress/useSaveProgress.ts index e7f66ad..5609a31 100644 --- a/src/hooks/saveProgress/useSaveProgress.ts +++ b/src/hooks/saveProgress/useSaveProgress.ts @@ -19,21 +19,27 @@ import React from 'react'; * * @returns [values, updateValues, clearValues] The data, a function to update the data, and a function to clear the data */ -const useSaveProgress = ({key, initialValues}: { key: string, initialValues?: any }) => { +const useSaveProgress = ({key, initialValues, storage}: { key: string, initialValues?: any, storage?: Storage }) => { const [values, setValues] = React.useState(() => { const saved = localStorage.getItem(key); const initialValue = JSON.parse(saved!); return initialValue || initialValues || {}; }); + // default to local storage + if (!storage) { + storage = localStorage; + } + // Helper function to save the data to local storage const saveValues = (value: any) => { - localStorage.setItem(key, JSON.stringify(value)); + storage?.setItem(key, JSON.stringify(value)); }; // Provide helper function to clear the data from local storage const clearValues = () => { - localStorage.removeItem(key); + setValues(initialValues || {}); + storage?.removeItem(key); }; // Provide helper function to update the data in local storage