I want to create a ticket functionality. On the main page (the parent) I have a axios get function that once the page is loaded, the useEffect is listing all the tickets components.
On the second page I have the child component where I imported with props the reloadTickets={fetchTickets}
method to be used every time I have added a new ticket.
The problem is that If I add a post, one time the post is not added, second time the post is added twice and third time the post is adding too many times on a single form submission. Sometime the post is not added at all, but after I try more times, the post is added twice and more.....
- This is my PARENT COMPOENTN
- This is my Child component
PS. Sorry for the pictures. But react code cannot be formated to look good on my page.
CodePudding user response:
Well the problem is you are not waiting for axios call to finish, since axios.post method is asynchronous. You need to make your function async and await axios.post method, here is an example how you can do this.
const createTicket = async (e) => {
e.preventDefault();
try {
await axios.post(postTicketURL, {
userID: userID,
content: ticketArea
}, configHeader);
await reloadTickets();
}
catch (error) {
console.log(error);
}
}
Update: I see that you are already using .then and .catch approach in your parent component, so you can solve this with that like this:
const createTicket = async (e: any) => {
e.preventDefault();
axios.post(postTicketURL, {
userID: userID,
content: ticketArea
}, configHeader).then((res: any) => {
console.log(res);
reloadTickets();
}).catch((err: any) => {
console.log(err);
});
}
But I would recommend async await approach, and also you should refactor your code inside TicketsComponent -> fetchTickets to match that. Why? Because async await is much more clear and modern approach and you are avoiding potential callback hell, for example if you now want to wait reloadTickets function to end properly. You can find out more about this topics here: https://www.loginradius.com/blog/async/callback-vs-promises-vs-async-await/