@reach/router#useParams TypeScript Examples

The following examples show how to use @reach/router#useParams. 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: general.tsx    From admin with MIT License 5 votes vote down vote up
GeneralBodyCard = ({ isEdit, product, ...props }) => {
  const params = useParams()
  const dialog = useImperativeDialog()
  const notification = useNotification()
  const updateProduct = useAdminUpdateProduct(params?.id)
  const deleteProduct = useAdminDeleteProduct(params?.id)

  const onDelete = async () => {
    const shouldDelete = await dialog({
      heading: "Delete Product",
      text: "Are you sure you want to delete this product",
    })
    if (shouldDelete) {
      deleteProduct.mutate(undefined, {
        onSuccess: () => {
          notification("Success", "Product deleted successfully", "success")
          navigate("/a/products/")
        },
        onError: (err) => {
          notification("Ooops", getErrorMessage(err), "error")
        },
      })
    }
  }

  const onStatusChange = async () => {
    const newStatus = product?.status === "published" ? "draft" : "published"
    updateProduct.mutate(
      {
        status: newStatus,
      },
      {
        onSuccess: () => {
          const pastTense = newStatus === "published" ? "published" : "drafted"
          notification(
            "Success",
            `Product ${pastTense} successfully`,
            "success"
          )
        },
        onError: (err) => {
          notification("Ooops", getErrorMessage(err), "error")
        },
      }
    )
  }

  const actionables = [
    {
      label: "Delete Product",
      onClick: onDelete,
      variant: "danger" as const,
      icon: <TrashIcon />,
    },
  ]

  return (
    <BodyCard
      actionables={isEdit ? actionables : undefined}
      forceDropdown
      status={
        isEdit ? (
          <StatusSelector
            isDraft={product?.status === "draft"}
            activeState="Published"
            draftState="Draft"
            onChange={onStatusChange}
          />
        ) : undefined
      }
      {...props}
    />
  )
}
Example #2
Source File: InviteView.tsx    From Frontend with MIT License 4 votes vote down vote up
InviteView: React.FC<RouteComponentProps> = () => {
  const { connectionMade } = useAnalytics();
  const { uid }: params = useParams();
  const location = useLocation();
  const toast = useToast();
  const intl = useIntl();
  const { profile } = useAuth();
  const [value, loading] = useObjectVal<Profile>(
    firebase.database().ref(`profiles/${uid}`)
  );
  const [
    createKnowsMutation,
    { loading: isLoadingConnection }
  ] = useCreateKnowsMutation({
    onCompleted() {
      connectionMade();
      toast({
        position: 'bottom-right',
        title: intl.formatMessage({ id: 'InviteView.Connected' }),
        description: intl.formatMessage(
          {
            id: 'InviteView.Connected-Description'
          },
          {
            name: value.displayName
          }
        ),
        status: 'success',
        isClosable: true
      });
    }
  });

  if (loading) {
    return <Spinner />;
  }

  const displayName = value && value.displayName ? value.displayName : 'user';
  const photoURL = value && value.photoURL ? value.photoURL : null;
  const shouldShowConnectButton = profile?.uid !== uid;

  return (
    <>
      <PageHeader
        heading={intl.formatMessage({ id: 'InviteView.heading' })}
        lead={intl.formatMessage(
          {
            id: 'InviteView.lead'
          },
          {
            name: value.displayName
          }
        )}
      />

      <AvatarGroup size="xl" max={2} mb={12}>
        <Avatar name={displayName} src={photoURL} />
        <Avatar bg="none" name="Contact Tracing" src={icon} />
      </AvatarGroup>
      {shouldShowConnectButton && (
        <Button
          isLoading={isLoadingConnection}
          width="200px"
          mb={16}
          variantColor="teal"
          onClick={() => {
            if (!profile) {
              navigate(`/me/sign-in?next=${location.pathname}`);
              return;
            }

            createKnowsMutation({
              variables: {
                fromUid: profile?.uid,
                toUid: uid
              }
            });
          }}
        >
          <FormattedMessage id="InviteView.Connect-button" />
        </Button>
      )}
      <Heading as="h3" mb={2} size="lg">
        <FormattedMessage id="InviteView.why-use" />
      </Heading>
      <List styleType="disc">
        <ListItem>
          <FormattedMessage id="InviteView.why-1" />
        </ListItem>
        <ListItem>
          <FormattedMessage id="InviteView.why-2" />
        </ListItem>
        <ListItem>
          <FormattedMessage id="InviteView.why-3" />
        </ListItem>
      </List>
    </>
  );
}
Example #3
Source File: index.tsx    From admin with MIT License 4 votes vote down vote up
EditPricesOverridesModal = ({
  close,
  product,
}: EditPricesOverridesModalProps) => {
  const context = useLayeredModal()
  const { id: priceListId } = useParams()
  const updatePriceList = useAdminUpdatePriceList(priceListId)
  const { store } = useAdminStore()

  const defaultPrices = store?.currencies.map((curr) => ({
    currency_code: curr.code,
    amount: 0,
  })) as MoneyAmount[]

  const getOnClick = (variant) => () =>
    context.push({
      title: `Edit price overrides`,
      onBack: () => context.pop(),
      view: (
        <PriceOverrides
          prices={mergeExistingWithDefault(
            variant.prices.filter((pr) => pr.price_list_id),
            defaultPrices
          )}
          isEdit
          defaultVariant={variant}
          variants={product.variants}
          onClose={close}
          onSubmit={(values) => {
            const updatedPrices = mapToPriceList(values, variant.id)

            updatePriceList.mutate(
              {
                prices: updatedPrices,
              },
              {
                onSuccess: () => {
                  context.pop()
                  close()
                },
              }
            )
          }}
        />
      ),
    })

  return (
    <LayeredModal isLargeModal context={context} handleClose={close}>
      <Modal.Body className="h-[calc(100vh-134px)] flex flex-col">
        <Modal.Header handleClose={close}>
          <h1 className="inter-xlarge-semibold">
            Price overrides{" "}
            <span className="text-grey-50 inter-xlarge-regular truncate">
              ({product.title})
            </span>
          </h1>
        </Modal.Header>

        <Modal.Content className="flex-1">
          <CollapsibleTree>
            <CollapsibleTree.Parent>
              <div>
                <img src={product.thumbnail} className="w-4 h-5 rounded-base" />
              </div>
              <span className="inter-small-semibold">{product.title}</span>
            </CollapsibleTree.Parent>
            <CollapsibleTree.Content>
              {product.variants.map((variant) => (
                <CollapsibleTree.Leaf>
                  <ProductVariantLeaf
                    key={variant.id}
                    onClick={getOnClick(variant)}
                    variant={variant}
                    prices={variant.prices.filter((pr) => pr.price_list_id)}
                  />
                </CollapsibleTree.Leaf>
              ))}
            </CollapsibleTree.Content>
          </CollapsibleTree>
        </Modal.Content>

        <Modal.Footer>
          <div className="flex w-full h-8 justify-end">
            <Button
              variant="ghost"
              className="mr-2 w-32 text-small justify-center rounded-rounded"
              size="large"
              onClick={close}
            >
              Cancel
            </Button>
            <Button
              disabled
              size="large"
              className="w-32 text-small justify-center rounded-rounded"
              variant="primary"
            >
              Save
            </Button>
          </div>
        </Modal.Footer>
      </Modal.Body>
    </LayeredModal>
  )
}