Im learning React and using the new implemented "Hooks" from Documentation. I got a problem with a Modal (Dialog from Material UI) and the open/close function using useEffect() function.
I have already read these both articles: React.useState does not reload state from props and How to sync props to state using React hook : setState()
It's already helped me, I have forgot to use the useEffect() function instead I was just setting the useState from what comes from props. Learned that useState will be executed only one time for setting the initial state. But I have however more one problem.
function AddItemModal(props) {
const [open, setOpen] = useState(props.isOpen);
useEffect(() => {
setOpen(props.isOpen);
}, [props.isOpen]);
function handleClose() {
setOpen(false);
}
That works for the first time when I click at the add button (in another Component) and handle the click (it changes the state to true) and I pass it as props to the Modal. But when I click (in modal) at close and try to click at add to open it again, nothing happens. In case needed, here's the code from the component where I handle the click and call the modal.
function ItemsTable() {
const [addModalOpen, setAddModalOpen] = React.useState(false);
const handleAddClick = () => {
setAddModalOpen(true);
};
<Box mt={4} position="fixed" bottom={10} right={10}>
<Fab color="secondary" aria-label="Add" onClick={handleAddClick}>
<AddIcon />
</Fab>
</Box>
<AddItemModal isOpen={addModalOpen} />