#Common Form

8 messages · Page 1 of 1 (latest)

chrome schooner
#

How could i dynamically pass an "action" name to a common form which works the same with muliple pages ?

const { data, error } = await actions[deleteAction]({
id: rawId,
});

or
const { data, error } = await actions[updateAction]({
id: rawId,

            });
unique flameBOT
#

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

#

To dynamically pass an action name to a common form that works across multiple pages in Astro, you can use the getActionPath() utility function. This approach allows you to create a reusable form component that can handle different actions based on the props passed to it.

Here's how you can implement this:

  1. First, create a common form component that accepts an action as a prop:
---
import { getActionPath } from 'astro:actions';

const { action, id } = Astro.props;
---

<form method="POST" action={getActionPath(action)}>
  <input type="hidden" name="id" value={id} />
  <button type="submit">Submit</button>
</form>

<script>
  import { actions } from 'astro:actions';

  const form = document.querySelector('form');
  form.addEventListener('submit', async (e) => {
    e.preventDefault();
    const formData = new FormData(form);
    const actionName = form.getAttribute('action').split('/').pop();
    const { data, error } = await actions[actionName](Object.fromEntries(formData));
    
    if (error) {
      console.error(error);
    } else {
      console.log(data);
      // Handle success
    }
  });
</script>
  1. Then, in your pages, you can use this common form component and pass the desired action:
---
import { actions } from 'astro:actions';
import CommonForm from '../components/CommonForm.astro';
---

<CommonForm action={actions.deleteAction} id="123" />
<CommonForm action={actions.updateAction} id="456" />

This approach allows you to reuse the same form component with different actions. The getActionPath() function is used to generate the correct action path for the form's action attribute, and the client-side script handles the form submission using the appropriate action based on the form's action attribute.

#

For more information on using getActionPath(), you can refer to the Astro Actions API Reference.

Remember that this approach requires your actions to be defined in the src/actions/index.ts file as described in the Organizing actions section of the Astro documentation.

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

#

@chrome schooner Kapa.ai is still learning and improving, please let me know how I did by reacting below.

chrome schooner
#

actionsupdateAction;

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type

#

Well ! your solution does not work !!

#

I have pasted the error message !!