npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@panter/react-forms

v1.0.6

Published

## Installation

Downloads

448

Readme

React Forms

Installation

You can install Prisma Inputs using npm or yarn:

yarn add @panter/react-forms

! Important NOTE !

This package is not transpiled jet. If you want to use it with next js you need to add this to your next.config.js:

const nextConfig = {
  transpilePackages: ["@panter/react-forms"]
  ...
}

useUploadFieldArray

The useUploadFieldArray custom hook is designed to integrate with React Hook Form's useFieldArray for managing the state of file uploads within a dynamic form array. This hook simplifies handling file uploads, including tracking upload progress, updating file information in the form, and removing files. It's particularly useful when you have a form that allows users to upload multiple files, and you need to keep the form state in sync with those uploads.

Parameters

The hook accepts an object with the following properties:

  • name: The name of the field array in the form. This corresponds to the field array you're managing with React Hook Form.
  • control: An optional control object from React Hook Form. This is used to control the form's state.
  • assetToInput: A function that transforms the uploaded file information or existing field data into the format expected by the form array. This function takes an object with an optional field (the current field data) and an optional file (the uploaded file data) and returns an object that can be used to update the form array.
  • uploader: A function that uploads the file.

## Returns The hook returns an object containing several properties and functions for managing file uploads:

  • update: A function to update a specific field in the field array.
  • updateFile: A function to handle updating the file for a specific field in the array. It takes the index of the field to update, the field data, and an optional FileList object. If a file is provided, it will be uploaded, and the field will be updated with the new file data.
  • uploadFiles: A function to handle uploading new files. It takes a FileList object, uploads the files, and appends the new file data to the form array.
  • currentUpdates: An array of objects representing the files currently being uploaded or updated. This can be used to display upload progress or status.
  • currentUploads: An array of objects representing the new files currently being uploaded. Similar to currentUpdates, this can be used to track the progress of new file uploads.
  • fields: An array of field data, similar to what is returned by React Hook Form's useFieldArray, but specifically tailored to include the _id key for tracking.
  • remove: A function to remove a specific field from the field array.

Usage

This hook is particularly useful in scenarios where you need to upload files as part of a form and maintain the state of those uploads within a dynamic array. It abstracts away the complexity of handling file uploads, progress tracking, and state updates, making it easier to integrate file uploads into your forms with React Hook Form.

Here's a simplified example of how you might use useUploadFieldArray in a component:

const MyFormComponent = () => {
  const { control } = useForm();
  const { fields, uploadFiles, updateFile, remove } = useUploadFieldArray({
    name: 'myFiles',
    control,
    assetToInput: ({ file }) => ({
      // Transform the uploaded file into the format expected by your form
      id: file.id,
      url: file.url,
      // Add any additional transformation logic here
    }),
    uploader: ({ file }) => upload(file),
  });

  return (
    <form>
      {fields.map((field, index) => (
        <div key={field.id}>
          {/* Render your file input or preview component here */}
          <button type="button" onClick={() => remove(index)}>
            Remove
          </button>
        </div>
      ))}
      <input
        type="file"
        multiple
        onChange={(e) => uploadFiles(e.target.files)}
      />
    </form>
  );
};

createGraphqlFormModal

Overview

The createGraphqlFormModal utility function simplifies creating forms that interact with GraphQL mutations. It provides a reusable way to handle form modals, with type safety powered by TypeScript.

Features

  • Streamlines form creation with GraphQL mutations.
  • Supports React Hook Form for efficient form handling.
  • Automatically infers types for mutation inputs and responses.
  • Handles modals for creating or updating data via GraphQL.

The createGraphqlFormModal pattern uses a factory approach to create type-safe form modal hooks. This two-step process is essential for several reasons:

  1. Type Safety: By creating a hook first, you can explicitly define the form model type that will be used in your UI, ensuring type safety throughout your form implementation.
  2. Type Inference: The factory pattern allows TypeScript to properly infer types from your GraphQL mutations and queries while maintaining the relationship with your form model.
  3. Separation of Concerns: It enables you to define your form model type separately from your GraphQL types, allowing for better data transformation and validation.

Usage Examples

Example createGraphqlFormModal

We'll demonstrate how to use the createGraphqlFormModal utility to handle a simple mutation using a modal form.

Step 1: Define the GraphQL Mutation

import { graphql } from '@apollo/client';
import { TypedDocumentNode } from '@apollo/client';

const AssignToProjectMutation = graphql(/* GraphQL */ `
  mutation AssignToProject($input: SplitFromOriginBcForProjectInput!) {
    assignBCToProject(input: $input) {
      id
      quantity
      quantityUnit
    }
  }
`) as TypedDocumentNode<
  { assignBCToProject: { id: string; quantity: number; quantityUnit: string } },
  { input: SplitFromOriginBcForProjectInput }
>;

type SplitFromOriginBcForProjectModel = {
  projectId: { id: string };
  quantity: number;
  quantityUnit: string;
};

Step 2: Create a Custom Hook with createGraphqlFormModal

The factory pattern used in createGraphqlFormModal serves a crucial purpose for TypeScript type inference and safety. Let's break down why this approach is valuable:

import { createGraphqlFormModal } from '@panter/react-forms';

const useAssignToProjectModal =
  createGraphqlFormModal<SplitFromOriginBcForProjectInput>();

Step 3: Use the Custom Hook in Your Component

import React, { useCallback } from 'react';
import { GraphqlFormModal } from '@panter/react-forms';
import { useTranslation } from 'react-i18next';
import { SendOutlined } from '@ant-design/icons';

export const useAssignToProject = () => {
  const { t } = useTranslation();

  const [handleOpenModal, formModalProps] = useAssignToProjectModal({
    mutation: AssignToProjectMutation,
    title: t('Assign Building Component to Project'),
    defaultValues: () => ({
      projectId: 'default-project-id',
      quantity: 5,
      quantityUnit: 'pcs',
    }),
    modelToInput: async (formModel) => ({
      input: { ...formModel, projectId: formModel.projectId.id },
    }),
    renderForm: ({ schemaForm }) => (
      <div>
        <input {...schemaForm.register('projectId')} placeholder="Project ID" />
        <input
          type="number"
          {...schemaForm.register('quantity')}
          placeholder="Quantity"
        />
        <input
          {...schemaForm.register('quantityUnit')}
          placeholder="Quantity Unit"
        />
      </div>
    ),
  });

  return { handleOpenModal, formModalProps };
};

Step 4: Integrate the Hook into a Component with a Button with @panter/react-forms-ant

import React from 'react';
import { useAssignToProject } from './useAssignToProject';
import { GraphqlFormModal } from '@panter/react-forms-ant';

export const AssignToProjectButton = () => {
  const { openModal, formModalProps } = useAssignToProject();

  return (
    <div>
      <button onClick={openModal}>Assign to Project</button>
      <GraphqlFormModal {...formModalProps} />
    </div>
  );
};

Example createGraphqlFormModalWithQuery

If you also need to run a query before opening the modal, use the createGraphqlFormModalWithQuery utility.

const useAssignToProjectWithQuery = createGraphqlFormModalWithQuery<SplitFromOriginBcForProjectInput>();

const [handleOpenModal, formModalProps] = useAssignToProjectWithQuery({
  mutation: AssignToProjectMutation,
  query: OneProjectQuery,
  title: 'Assign to Project with Query',
  defaultValues: () => ({
    projectId: { id: 'project-id' },
    quantity: 10,
    quantityUnit: 'pcs',
  }),
  modelToInput: async (formModel) => ({
    input: { ...formModel, projectId: formModel.projectId.id },
  }),
  renderForm: ({ schemaForm }) => (
    <div>
      <input {...schemaForm.register('project.id')} placeholder="Project ID" />
      <input type="number" {...schemaForm.register('quantity')} placeholder="Quantity" />
      <input {...schemaForm.register('quantityUnit')} placeholder="Quantity Unit" />
    </div>
  ),
});