Skip to content

Instantly share code, notes, and snippets.

@docentedev
Created November 29, 2022 20:08
Show Gist options
  • Save docentedev/11c52762ba03456aceb5d1891bdb9bec to your computer and use it in GitHub Desktop.
Save docentedev/11c52762ba03456aceb5d1891bdb9bec to your computer and use it in GitHub Desktop.
export const clearSessionStorage = () => {
for (const key in sessionStorage) {
if (key.includes('updateIfNewData__')) sessionStorage.removeItem(key);
}
};
clearSessionStorage();
const updateIfNewData = (
{ debug = false }: { debug: boolean } = { debug: false },
) => {
const tryUpdate = <T>(
key: string,
newData: T,
onChange: (data: T) => void,
isDebug?: boolean,
) => {
const log: {
key?: string;
oldData?: string | null;
data?: T;
action?: string;
} = {};
const internalKey = `updateIfNewData__${key}`;
const newDataString = JSON.stringify(newData);
const oldData = sessionStorage.getItem(internalKey);
if (debug || isDebug) log.key = internalKey;
if (debug || isDebug) log.oldData = oldData;
if (newDataString !== oldData) {
if (debug || isDebug) log.data = newData;
if (debug || isDebug) log.action = 'update';
sessionStorage.setItem(internalKey, newDataString);
onChange(newData);
if (debug || isDebug) console.log(log);
} else {
if (debug || isDebug) console.log(internalKey, 'same-data');
}
};
return tryUpdate;
};
export default updateIfNewData;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment