react-hook-form#UseFormGetValues TypeScript Examples

The following examples show how to use react-hook-form#UseFormGetValues. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AddProjectDialog.tsx    From backstage with Apache License 2.0 5 votes vote down vote up
AddProjectDialog = ({
  catalogEntities,
  open,
  handleClose,
  fetchBazaarProjects,
  fetchCatalogEntities,
}: Props) => {
  const bazaarApi = useApi(bazaarApiRef);
  const [selectedEntity, setSelectedEntity] = useState<Entity | null>(null);

  const defaultValues = {
    name: '',
    title: 'Add project',
    community: '',
    description: '',
    status: 'proposed' as Status,
    size: 'medium' as Size,
    responsible: '',
    startDate: null,
    endDate: null,
  };

  const handleEntityClick = (entity: Entity) => {
    setSelectedEntity(entity);
  };

  const handleSubmit: (
    getValues: UseFormGetValues<FormValues>,
    reset: UseFormReset<FormValues>,
  ) => Promise<void> = async (
    getValues: UseFormGetValues<FormValues>,
    reset: UseFormReset<FormValues>,
  ) => {
    const formValues = getValues();
    const response = await bazaarApi.addProject({
      ...formValues,
      entityRef: selectedEntity ? stringifyEntityRef(selectedEntity) : null,
      startDate: formValues.startDate ?? null,
      endDate: formValues.endDate ?? null,
    } as BazaarProject);

    if (response.status === 'ok') {
      fetchBazaarProjects();
      fetchCatalogEntities();
    }

    handleClose();
    reset(defaultValues);
  };

  return (
    <ProjectDialog
      handleSave={handleSubmit}
      title="Add project"
      isAddForm
      defaultValues={defaultValues}
      open={open}
      projectSelector={
        <ProjectSelector
          onChange={handleEntityClick}
          catalogEntities={catalogEntities || []}
          disableClearable={false}
          defaultValue={null}
          label="Select a project"
        />
      }
      handleClose={handleClose}
    />
  );
}
Example #2
Source File: VideoForm.hooks.ts    From atlas with GNU General Public License v3.0 4 votes vote down vote up
useVideoFormAssets = (
  watch: UseFormWatch<VideoWorkspaceVideoFormFields>,
  getValues: UseFormGetValues<VideoWorkspaceVideoFormFields>,
  setValue: UseFormSetValue<VideoWorkspaceVideoFormFields>,
  dirtyFields: FieldNamesMarkedBoolean<VideoWorkspaceVideoFormFields>
) => {
  const [thumbnailHashPromise, setThumbnailHashPromise] = useState<Promise<string> | null>(null)
  const [videoHashPromise, setVideoHashPromise] = useState<Promise<string> | null>(null)

  const { tabData } = useVideoWorkspaceData()

  const addAsset = useAssetStore((state) => state.actions.addAsset)
  const assets = watch('assets')
  const mediaAsset = useRawAsset(assets?.video.id || tabData?.assets.video.id || null)
  const thumbnailAsset = useRawAsset(assets?.thumbnail.cropId || null)
  const originalThumbnailAsset = useRawAsset(assets?.thumbnail.originalId || null)

  const hasUnsavedAssets = dirtyFields.assets?.video?.id || dirtyFields.assets?.thumbnail?.cropId || false

  const computeMediaHash = useCallback((file: Blob) => {
    const hashPromise = computeFileHash(file)
    setVideoHashPromise(hashPromise)
  }, [])

  const computeThumbnailHash = useCallback((file: Blob) => {
    const hashPromise = computeFileHash(file)
    setThumbnailHashPromise(hashPromise)
  }, [])

  useEffect(() => {
    if (!thumbnailAsset) {
      return
    }
    if (thumbnailAsset?.blob) {
      computeThumbnailHash(thumbnailAsset.blob)
    }
  }, [computeThumbnailHash, thumbnailAsset])

  useEffect(() => {
    if (!mediaAsset) {
      return
    }
    if (mediaAsset?.blob) {
      computeMediaHash(mediaAsset.blob)
    }
  }, [computeMediaHash, mediaAsset])

  const handleVideoFileChange = useCallback(
    (video: VideoInputFile | null) => {
      const currentAssetsValue = getValues('assets')

      if (!video) {
        setValue('assets', { ...currentAssetsValue, video: { id: null } }, { shouldDirty: true })
        return
      }

      const newAssetId = `local-video-${createId()}`
      addAsset(newAssetId, { url: video.url, blob: video.blob })

      const updatedVideo = {
        id: newAssetId,
        ...video,
      }
      const updatedAssets = {
        ...currentAssetsValue,
        video: updatedVideo,
      }
      setValue('assets', updatedAssets, { shouldDirty: true })
    },
    [addAsset, getValues, setValue]
  )

  const handleThumbnailFileChange = useCallback(
    (thumbnail: ImageInputFile | null) => {
      const currentAssetsValue = getValues('assets')

      if (!thumbnail) {
        setValue(
          'assets',
          { ...currentAssetsValue, thumbnail: { cropId: null, originalId: null } },
          { shouldDirty: true }
        )
        return
      }

      const newCropAssetId = `local-thumbnail-crop-${createId()}`
      addAsset(newCropAssetId, { url: thumbnail.url, blob: thumbnail.blob })
      const newOriginalAssetId = `local-thumbnail-original-${createId()}`
      addAsset(newOriginalAssetId, { blob: thumbnail.originalBlob })

      const updatedThumbnail = {
        ...thumbnail,
        cropId: newCropAssetId,
        originalId: newOriginalAssetId,
      }
      const updatedAssets = {
        ...currentAssetsValue,
        thumbnail: updatedThumbnail,
      }
      setValue('assets', updatedAssets, { shouldDirty: true })
    },
    [addAsset, getValues, setValue]
  )

  const files = useMemo(
    () => ({
      video: mediaAsset,
      thumbnail: {
        ...thumbnailAsset,
        ...(originalThumbnailAsset?.blob ? { originalBlob: originalThumbnailAsset?.blob } : {}),
      },
    }),
    [mediaAsset, originalThumbnailAsset?.blob, thumbnailAsset]
  )

  return {
    handleVideoFileChange,
    handleThumbnailFileChange,
    mediaAsset,
    thumbnailAsset,
    files,
    thumbnailHashPromise,
    videoHashPromise,
    hasUnsavedAssets,
  }
}
Example #3
Source File: EditProjectDialog.tsx    From backstage with Apache License 2.0 4 votes vote down vote up
EditProjectDialog = ({
  bazaarProject,
  openEdit,
  handleEditClose,
  handleCardClose,
  fetchBazaarProject,
}: Props) => {
  const classes = useStyles();
  const bazaarApi = useApi(bazaarApiRef);
  const [openDelete, setOpenDelete] = useState(false);
  const [defaultValues, setDefaultValues] = useState<FormValues>({
    ...bazaarProject,
    startDate: bazaarProject.startDate ?? null,
    endDate: bazaarProject.endDate ?? null,
  });

  const handleDeleteClose = () => {
    setOpenDelete(false);
    handleEditClose();

    if (handleCardClose) handleCardClose();
  };

  const handleDeleteSubmit = async () => {
    await bazaarApi.deleteProject(bazaarProject.id);

    handleDeleteClose();
    fetchBazaarProject();
  };

  useEffect(() => {
    setDefaultValues({
      ...bazaarProject,
      startDate: bazaarProject.startDate ?? null,
      endDate: bazaarProject.endDate ?? null,
    });
  }, [bazaarProject]);

  const handleEditSubmit: (
    getValues: UseFormGetValues<FormValues>,
  ) => Promise<void> = async (getValues: UseFormGetValues<FormValues>) => {
    const formValues = getValues();

    const updateResponse = await bazaarApi.updateProject({
      ...formValues,
      id: bazaarProject.id,
      entityRef: bazaarProject.entityRef,
      membersCount: bazaarProject.membersCount,
      startDate: formValues?.startDate ?? null,
      endDate: formValues?.endDate ?? null,
    });

    if (updateResponse.status === 'ok') fetchBazaarProject();
    handleEditClose();
  };

  return (
    <div>
      <ConfirmationDialog
        open={openDelete}
        handleClose={handleDeleteClose}
        message={[
          'Are you sure you want to delete ',
          <b key={bazaarProject.name} className={classes.wordBreak}>
            {bazaarProject.name}
          </b>,
          ' from the Bazaar?',
        ]}
        type="delete"
        handleSubmit={handleDeleteSubmit}
      />

      <ProjectDialog
        title="Edit project"
        handleSave={handleEditSubmit}
        isAddForm={false}
        defaultValues={defaultValues}
        open={openEdit}
        handleClose={handleEditClose}
        deleteButton={
          <Button
            color="primary"
            type="submit"
            className={classes.button}
            onClick={() => {
              setOpenDelete(true);
            }}
          >
            Delete project
          </Button>
        }
      />
    </div>
  );
}