Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kenmori/bd6115aa56285a5b5d4f06cc7b1bdce3 to your computer and use it in GitHub Desktop.
Save kenmori/bd6115aa56285a5b5d4f06cc7b1bdce3 to your computer and use it in GitHub Desktop.
【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