#Using Astro DB in React

4 messages · Page 1 of 1 (latest)

slim gorge
#

How do I perform actions on database(Astro DB) in a react components?

shadow solarBOT
#

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

#

To perform actions on Astro DB from a React component, you cannot directly access the database from within the React component itself. Instead, you should use Astro Actions or API endpoints as an intermediary between your React component and Astro DB.

Here’s the recommended approach based on the knowledge sources:

  1. Define Actions in Astro
    Create your database logic (e.g., insert, select) as an Astro Action. Actions provide type-safe backend functions that can be called from the client, including React components.

    Example action to insert a comment:

    // src/actions/index.ts
    import { db, Comment } from 'astro:db';
    import { defineAction } from 'astro:actions';
    import { z } from 'astro:schema';
    
    export const server = {
      addComment: defineAction({
        input: z.object({
          author: z.string(),
          body: z.string(),
        }),
        handler: async (input) => {
          const updatedComments = await db
            .insert(Comment)
            .values(input)
            .returning();
          return updatedComments;
        },
      }),
    };
    

    Astro DB: Query your database

  2. Call Actions from React
    In your React component, import the actions object from astro:actions and call your action as a function. This is supported and type-safe.

    Example usage in a React component:

    // src/components/AddComment.jsx
    import { actions } from 'astro:actions';
#

function AddComment() {
const handleSubmit = async (e) => {
e.preventDefault();
const author = e.target.author.value;
const body = e.target.body.value;
const { data, error } = await actions.addComment({ author, body });
if (!error) {
// handle success, e.g., update UI
} else {
// handle error
}
};

 return (
   <form onSubmit={handleSubmit}>
     <input name="author" placeholder="Author" />
     <textarea name="body" placeholder="Comment" />
     <button type="submit">Add Comment</button>
   </form>
 );

}

export default AddComment;

[Actions: Basic usage](<https://docs.astro.build/en/guides/actions/#basic-usage>)

**Important Notes:**
- You cannot import `.astro` components or Astro DB logic directly into a React component file. All database access must go through actions or endpoints.
- Actions handle input validation and return results or errors, making them ideal for use with React forms and interactivity.

If you need to fetch data (e.g., to display comments), you can also use actions or API endpoints to retrieve data and then use it in your React component.

For more details, see the [Astro Actions documentation](<https://docs.astro.build/en/guides/actions/#_top>) and [Astro DB guide](<https://docs.astro.build/en/guides/astro-db/#query-your-database>).
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------