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

Provide hooks for context-like access #7

Open
tyteen4a03 opened this issue Sep 12, 2024 · 4 comments
Open

Provide hooks for context-like access #7

tyteen4a03 opened this issue Sep 12, 2024 · 4 comments

Comments

@tyteen4a03
Copy link

It would be great if the package isn't limited to renderProps but instead can let child component access state via hooks.

@MiroslavPetrik
Copy link
Owner

Yeah, I saw the useActionState results pushed into Context API in the react conf by Sam Selikoff.

What are your use cases for this?

@MiroslavPetrik
Copy link
Owner

I have a preliminary version which can be installed npm i react-form-action@next.

Here is example usage

The render props are now accessible via the useFormContext() hook.

There is simple & reusable <Pending> component implemented.

Others can be defined easily:

import { useFormContext } from "react-form-action/client";

function DebugValidationError() {
  const { isInvalid, validationError } = useFormContext();

  return isInvalid && JSON.stringify(validationError);
}

@MiroslavPetrik
Copy link
Owner

I've refactored the Form from createForm, so its not coupled with the context.
Having context separate out of form element enables us to read the action state outside of it.

This is good for UI styling, for example when we want to display the progress around the form, etc.

This is just a sketch, but the ActionForm eventually should be just Form.

import { Action, ActionForm } from "react-form-action/client";

function SubscribeForm() {
  return (
      <Action action={subscribeAction} initialData={null}>
          <ActionForm>
            <input type="text" name="email" data-testid="email" />
            <button type="submit" data-testid="submit" />
          </ActionForm>
           {/* Read action state outside of <form> (ActionForm) */
          <ValidationError />
        </Action>
  );
}

@MiroslavPetrik
Copy link
Owner

Ok, finally the context can be used for convenient JSX components like the recently added ZodFieldError which takes "errors" and "name" prop.
Now, with the useActionContext() the "errors" prop can be added internally, so users only need to specify the field name:

image

image

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

No branches or pull requests

2 participants