Created
November 29, 2022 20:08
-
-
Save docentedev/11c52762ba03456aceb5d1891bdb9bec to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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