I have a Cancel button. I would like to perform a specific function in another js file when the button is pressed. Here is what I am doing.
function Add(props) {
const [cancel, setCancel] = useState(false);
const handleCancel = () => {
setCancel(true);
<UploadFile cancel={cancel}/>
}
return(
<div>
<Dialog open={open} onClose={handleClose}>
<DialogActions>
<Button variant="contained" onClick={handleCancel}>Cancel</Button>
</DialogActions>
</Dialog>
</div>
)
}
In another file UploadFile.js, the code as below:
const UploadFile = (props) => {
useEffect(() => {
if(props.cancel) {
remove();
}
},);
const remove = () => {
//Doing removing files
...
};
}
But the remove() is never called. I am not sure useEffect() is properly used.
2
Answers
You are calling the remove function inside useEffect, which only renders once when the page loads. This means the remove function would only be called when UploadFile renders. Try moving the if statement out of useEffect.
You should pass cancel prop as denpendency in useEffect to trigger update this useEffect.
Note: Do not put component inside handle logic functions