Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add EmptyString support for Formik compatibility #955

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

igorleszczynski
Copy link

Add EmptyString support for Formik compatibility

Description

Added support for generating Data Transfer Objects (DTOs) with empty string values instead of null values. This enhancement is particularly useful when working with Formik and Inertia.js in Laravel applications.

Features

  • New EmptyStringData trait and interface
  • Extended EmptyDataResolver with empty string support
  • Static method emptyString() that returns DTO with empty strings as default values

Use Case

When working with Formik forms in React + Inertia.js + Laravel applications, you often need to provide initial values for form fields. Using null values with Formik can cause errors as Formik expects string values for its form fields. Previously, you would need to:

// Before
UserStoreData::empty([
    'name' => '',
    'email' => '',
    'address' => '',
    // ... many more fields
]);

Now you can simply use:

// After
UserStoreData::emptyString();

This is particularly beneficial for large DTOs where manually defining empty values for each field would be tedious and error-prone.
Example with formik, spatie/laravel-typescript-transformer and inertia.js:

Controller:

public function create(): Response
{
    return Inertia::render('Users/UserStorePage', [
        'user' => UserStoreData::form(),
    ]);
}
const UserStorePage: React.FC<{user: UserStoreData}> = ({ user }) => {
    const handleUserStore = (values: UserStoreData, actions: FormikHelpers<UserStoreData>) => {
        /* store method content */
    };

    return <Formik initialValues={user} onSubmit={handleUserStore}>

    </Formik>
};

export default UserStorePage;

Changes

  • Added EmptyStringData trait and interface
  • Extended EmptyDataResolver with defaultValue parameter
  • Updated base Data class to implement EmptyStringData

Breaking Changes

None. This is a backwards-compatible enhancement.

@rrmesquita
Copy link

This is a really valid use case. I don't use Formik no more, but React complains as well, when input values transition from undefined to something else, stating that the input went from uncontrolled to controlled.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants