#Rendering async preact component

6 messages · Page 1 of 1 (latest)

vague gazelleBOT
#

Hi @soft aspen. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

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

soft aspen
#

@vague gazelle using preact-iso

vague gazelleBOT
#

Let me check the knowledge base for you. One moment! :books:

#

I'm sorry, but the provided knowledge sources do not contain any information about using preact-iso with Astro. However, you can refer to the official Preact documentation (https://preactjs.com/) or the Astro documentation (https://docs.astro.build/) for more information.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: