#Rendering async preact component
6 messages · Page 1 of 1 (latest)
To make async Preact components work, you can use the useState hook from Preact to manage the state of your component. Here's an example of how you can do this:
import { useState } from 'preact/hooks';
export default function Form() {
const [responseMessage, setResponseMessage] = useState("");
async function submit(e: SubmitEvent) {
e.preventDefault();
const formData = new FormData(e.target as HTMLFormElement);
const response = await fetch("/api/feedback", {
method: "POST",
body: formData,
});
const data = await response.json();
if (data.message) {
setResponseMessage(data.message);
}
}
return (
<form onSubmit={submit}>
<label>
Name
<input type="text" id="name" name="name" required />
</label>
<label>
Email
<input type="email" id="email" name="email" required />
</label>
<label>
Message
<textarea id="message" name="message" required />
</label>
<button>Send</button>
{responseMessage && <p>{responseMessage}</p>}
</form>
);
}
In this example, the useState hook is used to manage the responseMessage state. When the form is submitted, the submit function is called, which sends a POST request to the "/api/feedback" endpoint. The response from the server is then used to update the responseMessage state, which is displayed in the form.
You can find more information about this in the Astro documentation (https://docs.astro.build/en/recipes/build-forms-api/#recipe).
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@soft aspen kapa.ai is still learning and improving, please let us know how it did by reacting below
@vague gazelle using preact-iso
Let me check the knowledge base for you. One moment! :books: