Use callback to clear local storage on success (#462)

Co-authored-by: ekzyis <ek@stacker.news>
Co-authored-by: Keyan <34140557+huumn@users.noreply.github.com>
This commit is contained in:
ekzyis 2023-08-31 17:15:52 +02:00 committed by GitHub
parent 803acd1fc4
commit 6c203a4476
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 22 additions and 14 deletions

View File

@ -484,6 +484,21 @@ export function Form ({
}
}, [])
function clearLocalStorage (values) {
Object.keys(values).forEach(v => {
window.localStorage.removeItem(storageKeyPrefix + '-' + v)
if (Array.isArray(values[v])) {
values[v].forEach(
(iv, i) => {
Object.keys(iv).forEach(k => {
window.localStorage.removeItem(`${storageKeyPrefix}-${v}[${i}].${k}`)
})
window.localStorage.removeItem(`${storageKeyPrefix}-${v}[${i}]`)
})
}
})
}
// if `invoiceable` is set,
// support for payment per invoice if they are lurking or don't have enough balance
// is added to submit handlers.
@ -491,7 +506,7 @@ export function Form ({
// and use them as variables in their GraphQL mutation
if (invoiceable && onSubmit) {
const options = typeof invoiceable === 'object' ? invoiceable : undefined
onSubmit = useInvoiceable(onSubmit, options)
onSubmit = useInvoiceable(onSubmit, { callback: clearLocalStorage, ...options })
}
return (
@ -506,18 +521,7 @@ export function Form ({
if (onSubmit) {
const options = await onSubmit(values, ...args)
if (!storageKeyPrefix || options?.keepLocalStorage) return
Object.keys(values).forEach(v => {
window.localStorage.removeItem(storageKeyPrefix + '-' + v)
if (Array.isArray(values[v])) {
values[v].forEach(
(iv, i) => {
Object.keys(iv).forEach(k => {
window.localStorage.removeItem(`${storageKeyPrefix}-${v}[${i}].${k}`)
})
window.localStorage.removeItem(`${storageKeyPrefix}-${v}[${i}]`)
})
}
})
clearLocalStorage(values)
}
} catch (err) {
console.log(err)

View File

@ -131,6 +131,7 @@ const MutationInvoice = ({ id, hash, hmac, errorCount, repeat, onClose, expiresA
const defaultOptions = {
forceInvoice: false,
requireSession: false,
callback: null // (formValues) => void
replaceModal: false
}
export const useInvoiceable = (onSubmit, options = defaultOptions) => {
@ -156,7 +157,10 @@ export const useInvoiceable = (onSubmit, options = defaultOptions) => {
const repeat = () =>
// call onSubmit handler and pass invoice data
onSubmit({ satsReceived, hash, hmac, ...formValues }, ...submitArgs)
.then(onClose)
.then(() => {
onClose()
options?.callback?.(formValues)
})
.catch((error) => {
// if error happened after payment, show repeat and cancel options
// by passing `errorCount` and `repeat`