There is no problem in adding the because I successfully added data to my database but the problem is need to refresh the page before getting the updated data. this is the code ive done so far, this is the current error, did i miss something in my code? please help
note:
The child component will add data and the parent component will display the latest data that the child component inserted
parent
const OvertimeType = () => {
const [reRender, setRerender] = useState(false);
....
const fetchData = async () => {
const response = await getDepartmentData('All', 100, 0);
response.data.map(function(u){
.....
})
}
useEffect(() => {
fetchData();
}, [reRender]);
const HandleAdd = (val) =>{
setRerender(val);
}
return (
<CustomToolbar sendToParent={HandleAdd()}/>
)
...
}
//
child
class CustomToolbar extends React.Component {
state = false;
HandleAdd = () => {
Swal.fire({
title: 'Add Over Time',
text: "Input overtime name below.",
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Save',
html: generateInputForms({
strname: '',
intsequence: ''
}),
preConfirm: () => {
let strname = document.getElementById('strname').value;
let intsequence = document.getElementById('intsequence').value;
if (!strname) {
Swal.showValidationMessage('This field is required.')
}
if (!intsequence) {
Swal.showValidationMessage('This field is required.')
}
return {
strname: document.getElementById('strname').value,
intsequence: document.getElementById('intsequence').value
}
}
}).then((result) => {
if (result.isConfirmed) {
let request = {
strname:document.getElementById('strname').value,
intsequence:document.getElementById('intsequence').value
}
addDepartment(request).then(res =>{
if (res.status == 200){
Swal.fire({
icon: 'success',
title: 'Over Time',
text: 'New Data has been added successfully.',
}).then(res => {
this.sendToParent(res);
})
}else{
Swal.fire({
icon: 'error',
title: 'Oops',
text: 'Something went wrong.',
})
}
})
}
})
}
render() {
const { classes } = this.props;
return (
<React.Fragment>
<Tooltip title={"Add"}>
<Button
variant="contained"
onClick={this.HandleAdd}
className={classes.button}
startIcon={<AddIcon className={classes.addIcon} style={{color: '#fff',}} />}
>
Add
</Button>
</Tooltip>
</React.Fragment>
);
}
}
CodePudding user response:
The problem is probably the way you pass the function
<CustomToolbar sendToParent={HandleAdd()}/>
A callback function should be sent like this without the parenthesis:
<CustomToolbar sendToParent={HandleAdd}/>
CodePudding user response:
I see two issues here. First, as a few others have noted you'll want to pass the function, not invoke it.
<CustomToolbar sendToParent={HandleAdd}/>
Second, in this implementation sendToParent
is defined on props
, rather than a function in the class. To access it, you'll need to invoke it on this.props
.
this.props.sendToParent(res);