Here is the CodeSandbox: https://codesandbox.io/s/competent-dream-8lcrt
I have implemented a modal with React context which exposes 1) the open state 2) the modal config 3) an open and close method
// ...
const onOpenDialog = (mode, config) => {
setDialogMode(mode)
if (config) {
setDialogConfig(config);
}
}
const onCloseDialog = () => {
setDialogMode("");
if (Object.keys(dialogConfig).length > 0) {
setDialogConfig({})
}
}
// ...
return (
<Provider value={{ dialogMode, dialogConfig, onOpenDialog, onCloseDialog }}>
{children}
</Provider>
)
From the main component, I have an onClick handler that call the onOpenDialog method and pass an onSubmit and onClose callback in its config object (this onCloseDialog callback is the issue)
const { onOpenDialog, onCloseDialog } = useDialog()
// ...
const onClick = () => {
onOpenDialog("add", {
data: null,
onSubmit: (data) => {
console.log("Form Data: ", data)
},
onCancel: onCloseDialog
})
}
And finally, I have a FormInModal component that call the two callbacks passed in the dialogConfig object when hitting submit and close.
const onSubmit = (data) => {
dialogConfig.onSubmit({
username: data.username,
password: data.password
})
}
const onCancel = () => {
dialogConfig.onCancel()
}
Steps to reproduce:
OpenTo be fair 3. works half of the time. This is weird because the dialogConfig state is always updated when the dialog opens. You can see on the React Dev tool that the state update only half the time
This is a known problem in React when trying to access the state from a function closures. The old state is captured at the closure creation and returned by the function even though the state has updated.
One way to solve the issue is to access the updated state with:
setState(previousState => newState) instead of setState(newState)
The answer from the react community: Function that read an outdated sate