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

Support for ZodIntersection (and maybe ZodUnion?) #34

Open
solomonhawk opened this issue May 2, 2023 · 2 comments · May be fixed by #36
Open

Support for ZodIntersection (and maybe ZodUnion?) #34

solomonhawk opened this issue May 2, 2023 · 2 comments · May be fixed by #36

Comments

@solomonhawk
Copy link

Similar to #25, if your schema is a z.intersection(schema1, schema2) or z.union([...schemas]), it won't work with the hook.

As you know, these schemas can get pretty complicated. In the case of intersection there are 2 branches of other zod types to collect fields from. Here's an initial stab that seems to work ok for my use case but could definitely be improved:

function getShapeFromZodType(schema: ZodType, shape: any = {}) {
  if (schema instanceof ZodObject) {
    for (const key of Object.keys(schema.shape)) {
      shape[key] = schema.shape[key]
    }

    return shape
  }

  if (schema instanceof ZodEffects) {
    return getShapeFromZodType(schema._def.schema, shape)
  }

  if (schema instanceof ZodIntersection) {
    return {
      ...getShapeFromZodType(schema._def.left, shape),
      ...getShapeFromZodType(schema._def.right, shape),
    }
  }
}

export function useFormInputProps(schema: ZodType) {
  const shape = getShapeFromZodType(schema)

  return function props(key: string) {
    const def = shape[key]
    if (!def) {
      throw new Error(`no such key: ${key}`)
    }
    return getInputProps(key, def)
  }
}
@kiliman
Copy link
Owner

kiliman commented May 2, 2023

Yes, my schema support really only handled the stuff I used or added due to other user requests.

I should go back and see if I can figure out a more general way to handle any zod schema.

solomonhawk added a commit to solomonhawk/remix-params-helper that referenced this issue May 2, 2023
solomonhawk added a commit to solomonhawk/remix-params-helper that referenced this issue May 2, 2023
solomonhawk added a commit to solomonhawk/remix-params-helper that referenced this issue May 2, 2023
@solomonhawk
Copy link
Author

solomonhawk commented May 16, 2023

Unions are an interesting case - I don't think we can reasonably extract input props from any union, given the associated schemas could have conflicting rules.

We can handle Discriminated Unions but it requires passing in data (the current value of the discriminant). I actually have an implementation of this that works.

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