Examples
Like Button

Like Button Example

In this example, we will create a simple like button that toggles between liking and unliking a post.

"use server";
 
import { createActionWithState } from 'better-react-server-actions';
import { z } from 'zod';
 
export const login = createActionWithState({
  stateSchema: z.object({
    likeId: z.string().optional(),
  }),
  requestHandler: async ({ likeId }) => {
    // Check if user is logged in
    // and redirect to login page if not
 
    if (likeId) {
      // Delete like via api
      return {
        likeId: undefined,
      }
    } else {
      // Create like via api
      const newLikeId = 'new-like-id';
      return {
        likeId: newLikeId,
      }
    }
  }
});
"use client";
 
import { useActionState } from 'react';
import { toggleLike } from './action';
 
export default function Page() {
  const [state, action] = useActionState(toggleLike, {});
 
  return (
    <form action={action}>
      <button>
        {state.likeId ? 'Unlike' : 'Like'}
      </button>
    </form>
  )
}

Try it out

Open in a new tab (opens in a new tab)