When I submit an object/issue I am calling a function of the parent component, which has been passed to the child component as props. After sending my data I want to clear my input fields. The Problem is, that I am clearing my input fields immediately after calling addNewIssue(). I actually want to wait until the POST-Call has resolved.
If I only had one component I could just clear the input fields after e.g. setissueList(newIssueList), since state and rest-call would be in the same component.
How can I notify the child component that the POST-Call has resolved and only then it should clear the inputs?
I tried to google this problem, but I couldn't find anything. Most likely I am not using the right words. I assume it has to do something with promises and the solution might be simple but I am not an expert regarding promises or async.
// parent component
const addNewIssue = (issue) => {
axios.post(url '/forms/issue', issue, headers).then((res) => {
let newIssueList = [...issueList, res.data];
setissueList(newIssueList);
});
}
<NewIssue addNewIssue={addNewIssue} />
// child component
const const handleSubmit = (e) => {
e.preventDefault();
addNewIssue(inputs);
setInputs({
summary: "",
description: ""
});
}
CodePudding user response:
Use your API request along with a callback
// parent component
const addNewIssue = (issue,cb) => {
axios.post(url '/forms/issue', issue, headers).then((res) => {
let newIssueList = [...issueList, res.data];
setissueList(newIssueList);
cb()
});
}
<NewIssue addNewIssue={addNewIssue} />
// child component
const const handleSubmit = (e) => {
e.preventDefault();
const cb=()=>{setInputs({
summary: "",
description: ""
});}
addNewIssue(inputs,cb);
}