diff --git a/package-lock.json b/package-lock.json index c806faf..e102f3d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "save-progress", - "version": "1.0.6", + "version": "1.0.7", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "save-progress", - "version": "1.0.6", + "version": "1.0.7", "license": "MIT", "dependencies": { "typescript": "^4.9.3" diff --git a/package.json b/package.json index 68c07f0..c0591ba 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@crispice/save-progress", - "version": "1.0.6", + "version": "1.0.7", "description": "A React hook to save progress in a form, or any other scenario, and restore it when the user returns to the form. It uses localStorage to save the progress.", "main": "dist/cjs/index.js", "module": "dist/esm/index.js", diff --git a/src/hooks/saveProgress/useSaveProgress.ts b/src/hooks/saveProgress/useSaveProgress.ts index 5609a31..72688dd 100644 --- a/src/hooks/saveProgress/useSaveProgress.ts +++ b/src/hooks/saveProgress/useSaveProgress.ts @@ -16,30 +16,26 @@ import React from 'react'; * * @param key The key to use to save the data in local storage * @param initialValue The initial value to use if there is no data in local storage + * @param storage The storage to use, defaults to local storage * * @returns [values, updateValues, clearValues] The data, a function to update the data, and a function to clear the data */ const useSaveProgress = ({key, initialValues, storage}: { key: string, initialValues?: any, storage?: Storage }) => { const [values, setValues] = React.useState(() => { - const saved = localStorage.getItem(key); + const saved = (storage ?? 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) => { - storage?.setItem(key, JSON.stringify(value)); + (storage ?? localStorage).setItem(key, JSON.stringify(value)); }; // Provide helper function to clear the data from local storage const clearValues = () => { setValues(initialValues || {}); - storage?.removeItem(key); + (storage ?? localStorage).removeItem(key); }; // Provide helper function to update the data in local storage