How I Handle Pocketbase Fields Errors

As I’m using Pocketbase at work for a new project to collect applicant data, I need to handle field validation errors effectively. I want to use Pocketbase’s default error messages when creating or updating records in a collection. To achieve this, I wrote a function to extract error messages from fields when a Pocketbase error occurs.

import { ClientResponseError } from "pocketbase";

export function isFieldError(error: unknown, key: string) {
  return error instanceof ClientResponseError
    ? error.response.data[key]?.message
    : null;
}

Note: ClientResponseError is the type of error that Pocketbase throws whenever an error occurs.

In this project’s case, I’m using Astro with React for the dynamic parts of the application.

I use this function with useMemo to manage field errors:

const fieldErrors = useMemo(() => {
  return {
    name: isFieldError(error, "name")
    // ... other fields in your collection
  };
}, [error]);

Here’s an example of how to use it with NextUI:

// ...
<Input
  name="name"
  label="Name"
  isRequired
  placeholder="Enter Name"
  errorMessage={fieldErrors.name}
  isInvalid={!!fieldErrors.name}
/>
// ...

By using this approach, I can easily handle and display field-specific error messages.