I have a function with two arrows, which sends some form data to my api via a POST request with fetch, once the form gets submitted. I want to make fetch asynchronous, but I really have no clue where the async keyword goes in this case.
//handles the submitting process
const handleSubmit = async (form_username, form_email, form_password) => (event) => {
event.preventDefault();
let data = {
username: form_username,
email: form_email,
password: form_password,
};
const response = await fetch(API + "/register", {
method: "POST",
mode: "cors",
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
},
body: JSON.stringify(data),
});
};
The function would then be called via handleSubmit(param1, param2,...);
However, having the async keyword infront of the first params list returns the error unexpected reserved word 'await'
Any ideas where I should place the async keyword in order to actually make it async? Thanks in advance!
Your async is declared on the wrong function: it should be the inner function that is being returned, since it is the one that contains the await keyword:
const handleSubmit = (form_username, form_email, form_password) => async (event) => {
// Rest of the logic here
}