bami
bami

Reputation: 299

Do we need server actions in next js, even when not using next js for back-end?

I'm new at server actions in Next js and I'm just learning.According to https://blog.logrocket.com/diving-into-server-actions-next-js-14/, assume that we have to do list using Next 14 and we use server actions :

// app/page.tsx
import { createClient } from '@supabase/supabase-js';
export default function TodoList() {

  const addTodo = async (formData: FormData) => {
    'use server';
    const supabaseUrl = 'YOUR_SUPABASE_URL';
    const supabaseKey = process.env.SUPABASE_KEY;
    const supabase = createClient( supabaseUrl, supabaseKey);
    const todoItem = formData.get('todo');
    if (!todoItem) {
      return;
    }
    // Save todo item to database
    const { data, error } = await supabase.from('todos').insert({
      todo: todoItem,
    });
  };

  return (
    <>
     <h2>Server Actions Demo</h2>
        <div>
          <form action={addTodo} method="POST">
            <div>
              <label htmlFor="todo">Todo</label>
              <div>
                <input id="todo" name="text" type="text"
                  placeholder="What needs to be done?"
                  required
                />
              </div>
            </div>
            <div>
              <button type="submit"> Add Todo</button>
            </div>
          </form>
        </div>
    </>
  );
}

As the document says server actions simplifies submitting form in server component. But what if the back-end is not written on my own and not using Next js. for example if I use ASP.net or PHP for back-end, what is the advantage of using server actions? In another words is server action only for people who use next js for back-end? or It is independent of back-end language?

Upvotes: -1

Views: 367

Answers (1)

Neer Amrutia
Neer Amrutia

Reputation: 11

Server actions are for React frameworks. Server Actions are a way to call server-side code in React's client-side rendering. A simple example of server Actions:

'use server'
 
export async function updateUser(userId, formData) {
  // ...
}

They can be used in Server and Client Components to handle form submissions and data mutations in Next.js applications. Ref : https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations

Upvotes: 0

Related Questions