CREAT

Trigger Function (client) —> Action Function (server) —> Mutation Function (server)

Trigger function

Purpose:

  1. Handle user activities: set states to prevent repeating submission
  2. Handle page performance: refresh page when submission success

Principle:

Show more logic, less code details.

Code sample:

Below is a code example of creating an object from clicking a submit button in a form in an object editor works both for creating and updating.

import { mutate } from 'swr';

const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    setIsSubmitting(true);
    e.preventDefault();
    if (isCreating) {
      await addCommentAction(formData, userID);
    } else {
      await updateCommentAction(formData, userID);
    }
    setIsSubmitting(false);
    mutate(['comments', userID]); // for updating the list of articles
    closeModal(); // in this example, creating and editing are in a same editor that shows as a modal
  };

Action Function

Purpose:

  1. Check user session
  2. Clear queries flow: add comment to db, then probably update ‘user_comment’, etc
  3. Data structure transformation
  4. Log server infos

Principle:

Show more logic, less code details.

Code sample: