Skip to content

Instantly share code, notes, and snippets.

@edoves
Last active November 19, 2024 13:34
Show Gist options
  • Save edoves/dcfcca9790cfb1d83d4de9b50055e15c to your computer and use it in GitHub Desktop.
Save edoves/dcfcca9790cfb1d83d4de9b50055e15c to your computer and use it in GitHub Desktop.
Server Action with manual validation

Server Action with manual validation

Video Source

textarea.jsx

'use client';

import { useState } from 'react';
import { actionFeedback } from './_action';

function Textarea() {
  const [error, setError] = useState<string>('');

  const clientAction = async (formData: FormData) => {
    const { error, feedbackData } = await actionFeedback(formData);

    if (error) {
      setError(error);
    } else {
      setError('');
      console.log(feedbackData);
    }
  };
  
  return (
    <form action={clientAction}>
      <textarea name="feedback"></textarea>
      <button type="submit">submit</button>     
    </form>
  )
}

export default Textarea


We need to turn the type feedbackData and the error in our function

_action.ts

'use server';

type FeedBackData = {
  feedbackData?: string;
  error?: string;
};

export async function actionFeedback(formData: FormData): Promise<Feed> {
  let feedback = formData.get('feedback') as string;

  if (!feedback || feedback.length <= 100) {
    return { error: 'Feed back must be 100 characters long' };
  }

  return { feedbackData: feedback };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment