I’ve got a state to show a dialog inside a React
const [isConfirmationDialogVisible, setConfirmationDialogVisibility] = useState(false);
I set the visibility state when a button is clicked:
<Button id={item.id}
onPressCallback={() => setConfirmationDialogVisibility(true)} />
The visibility state is passed on to the dialog like this (isOwnItem is true):
<> ...
{isOwnItem && <Dialog
id={item.content.id}
visible={isConfirmationDialogVisible}
/>}
</>
The visibility property is set inside the dialog from the dialog properties:
const [isVisible, setVisibility] = useState(props.visible);
and is passed on to an alert like this:
<StyledAlert show={isVisible} ... />
The alert has worked before, so I think the problem is not there.
Now, when I click the button, nothing happens. Help would be greatly appreciated!
2
Answers
I added a console output to the onPressCallback of the button and realised that isVisible was always false when the button was pressed.
I have solved it now by adding the isVisible condition to the part where I call the dialog:
By setting it into state (with
useState
), the value forprops.visible
will be set only on mount. It’s an inital value, it won’t be updated byprops.visible
changing; it will only update whensetVisibility
is called.When
Dialog
mounts, it will get the correct value, but new value set bysetConfirmationDialogVisibility
won’t update the value ofisVisible
If you need to change the state from inside
Dialog
, pass the state setter:If not, you could simply do away with setting the inner state:
If you really must keep the inner state, AND you don’t want to pass the parent state setter, then you need a useEffect that updates the inner state when the outer state changes:
NOTE: I would not recommend this last method as there is a lot of redundant code