Skip to content

Commit

Permalink
add option to choose storage
Browse files Browse the repository at this point in the history
either localStorage and sessionStorage
  • Loading branch information
murageh committed Feb 6, 2023
1 parent 2d7bcad commit e0fa161
Showing 1 changed file with 9 additions and 3 deletions.
12 changes: 9 additions & 3 deletions src/hooks/saveProgress/useSaveProgress.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit e0fa161

Please sign in to comment.