Skip to content

Instantly share code, notes, and snippets.

@ELI7VH
Last active October 7, 2020 22:44
Show Gist options
  • Save ELI7VH/d2c0f4166d85203cab0bb36461c807aa to your computer and use it in GitHub Desktop.
Save ELI7VH/d2c0f4166d85203cab0bb36461c807aa to your computer and use it in GitHub Desktop.
// TO USE THIS:
import { useEffect, useState } from 'react'
import { FormInstance } from 'antd/lib/form'
type Props<T> = {
form: FormInstance<T>
id: string // some unique identifier that matches whatever you're editing
}
export const useFormState = <T>({ type, form }: Props<T>) => {
const [state, setState] = useState<T | null>(null)
useEffect(() => {
const handleBeforeunload = () => {
update<T>(type, form.getFieldsValue())
}
window.addEventListener('beforeunload', handleBeforeunload)
return () => {
window.removeEventListener('beforeunload', handleBeforeunload)
}
}, [type, form])
const update = <T>(type: FormType, body: T) => {
console.log(`updating localStorage.forms/${type}`, body)
window.localStorage.setItem(`forms/${type}`, JSON.stringify(body))
}
const clear = () => {
console.log(`clearing localStorage.forms/${type}`)
window.localStorage.removeItem(`forms/${type}`)
}
useEffect(() => {
const storage = window.localStorage.getItem(`forms/${type}`)
console.log(`getting localStorage.forms/${type}`, storage)
if (!storage) return
setState(JSON.parse(storage))
}, [type])
useEffect(() => {
if (state) {
form.setFieldsValue(state as any)
}
}, [form, state])
return { state, update, clear }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment