Search code examples
javascriptreactjsreact-routerreact-props

React - Navigation Prompt onConfirm gets triggered straight away


I have an issue where I need to show a navigationPrompt when use tries to re-route (that works). But the onConfirm function gets called immediately before I hit the "Confirm" button. I want to setReload(true)AFTER the user presses the "confirm" button.

<NavigationPrompt onConfirm={setReload(true)} when={myExampleFunction}>
                    {({ onConfirm, onCancel }) => (
                        <React.Fragment>
                            <Modal
                                ariaHideApp={false}
                                style={customStyles}
                                isOpen={true}
                            > You are about to lose all the data
            <button onClick={onCancel}>Cancel</button>
                                <button onClick={onConfirm}>Confirm</button>
                            </Modal>
                        </React.Fragment>
                    )}
                </NavigationPrompt>

Solution

  • The problem is that you are calling setReload with setReload(true) on mount.

    You need to pass a function, and not call it there:

    onConfirm={() => setReload(true)} // A new function to be called onConfirm