Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
【React Hooks】modules for reload and tab close which react-router prompt cannot support

【React Hooks】 modules for reload and tab close which react-router prompt cannot support

react-routerのPromptではreloadとtabクローズに対応できなさそうなので作った

isDuty ・・・A flag that determines if the user has edited the value of the form. got from formik etc.

// in /modules/useUnloadEffect

import * as React from 'react'

const setupBeforeUnloadListener = (isDuty: boolean) => {
    if (isDuty) {
        window.onbeforeunload = () => true
    } else {
        window.onbeforeunload = null
    }
}
export const useUnloadEffect = (isDuty: boolean) => {
    React.useEffect(() => {
        setupBeforeUnloadListener(isDuty)
    }, [isDuty])
}

//////////// use modules
import * as modules from '/modules/useUnloadEffect'

...

modules.useUnloadEffect(isDuty)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment