react#useCallback TypeScript Examples

The following examples show how to use react#useCallback. 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: DeleteDialog.tsx    From vscode-crossnote with GNU Affero General Public License v3.0 7 votes vote down vote up
export function DeleteDialog(props: Props) {
  const { t } = useTranslation();
  const note = props.note;

  const deleteNote = useCallback((note: Note) => {
    vscode.postMessage({
      action: MessageAction.DeleteNote,
      data: note,
    });
  }, []);

  return (
    <Dialog open={props.open} onClose={props.onClose}>
      <DialogTitle>{t("delete-file-dialog/title")}</DialogTitle>
      <DialogContent>
        <DialogContentText>
          {t("delete-file-dialog/subtitle")}
        </DialogContentText>
      </DialogContent>
      <DialogActions>
        <Button
          style={{ color: "red" }}
          onClick={() => {
            deleteNote(note);
            props.onClose();
          }}
        >
          {t("general/Delete")}
        </Button>
        <Button onClick={props.onClose}>{t("general/cancel")}</Button>
      </DialogActions>
    </Dialog>
  );
}
Example #2
Source File: usePagination.tsx    From one-platform with MIT License 7 votes vote down vote up
usePagination = ({ page = 1, perPage = 20 }: Props): UsePaginationReturn => {
  const [pagination, setPagination] = useState({ page, perPage });

  const onSetPage = useCallback((pageNumber: number): void => {
    setPagination((state) => ({ ...state, page: pageNumber }));
  }, []);

  const onPerPageSelect = useCallback((perPageSelected: number) => {
    setPagination((state) => ({ ...state, perPage: perPageSelected }));
  }, []);

  const onResetPagination = useCallback(() => {
    setPagination({ page, perPage });
  }, [page, perPage]);

  return {
    pagination,
    onSetPage,
    onPerPageSelect,
    onResetPagination,
  };
}
Example #3
Source File: index.tsx    From vscode-crossnote with GNU Affero General Public License v3.0 6 votes vote down vote up
function GitHubGistWidget(props: WidgetArgs) {
  const classes = useStyles(props);
  const { t } = useTranslation();
  const [url, setURL] = useState<string>("");

  const setGistURL = useCallback(
    (url: string) => {
      try {
        const location = new URL(url);
        if (location.host !== "gist.github.com") {
          return;
        } else {
          props.setAttributes({
            url: location.origin + location.pathname,
          });
        }
      } catch (error) {}
    },
    [props]
  );

  if (props.attributes["url"]) {
    return (
      <Box className={"preview github-gist"} style={{ whiteSpace: "normal" }}>
        <Gist url={props.attributes["url"]}></Gist>
        {!props.isPreview && (
          <Box className={clsx(classes.actionButtonsGroup)}>
            <IconButton onClick={() => props.removeSelf()}>
              <TrashCanOutline></TrashCanOutline>
            </IconButton>
          </Box>
        )}
      </Box>
    );
  }

  if (props.isPreview) {
    return null;
  }

  return (
    <Card elevation={2} className={clsx(classes.card)}>
      <Typography variant={"h5"}>
        {t("widget/crossnote.github_gist/title")}
      </Typography>
      <TextField
        label={t("widget/crossnote/github_gist/enter-github-gist-url")}
        placeholder={"https://gist.github.com/..."}
        value={url}
        onChange={(event) => setURL(event.target.value)}
        fullWidth={true}
        onKeyUp={(event) => {
          if (event.which === 13) {
            setGistURL(url);
          }
        }}
      ></TextField>
      <Box className={clsx(classes.actionButtonsGroup)}>
        <Tooltip title={t("general/Delete")}>
          <IconButton onClick={() => props.removeSelf()}>
            <TrashCan></TrashCan>
          </IconButton>
        </Tooltip>
      </Box>
    </Card>
  );
}
Example #4
Source File: useToggle.tsx    From one-platform with MIT License 6 votes vote down vote up
useToggle = (initialState = false): UseToggleReturn => {
  const [value, setValue] = useState(initialState);

  const on = useCallback(() => {
    setValue(true);
  }, []);

  const off = useCallback(() => {
    setValue(false);
  }, []);

  const toggle = useCallback((isOpen?: boolean) => {
    setValue((prev) => (typeof isOpen === 'boolean' ? isOpen : !prev));
  }, []);

  return [value, { on, off, toggle }];
}
Example #5
Source File: homeRouter.tsx    From react_admin with MIT License 6 votes vote down vote up
Routers: React.FC<Iprops> = props => {
  /**
   * 切换路由触发
   * 模拟vue的路由守卫
   */
  const onEnter = useCallback(Component => {
    return <Component {...props} />
  }, [])

  return (
    <ErrorBoundary location={props.location}>
      <Suspense fallback={<Loading />}>
        <Switch>
          <Route exact path="/home" render={() => onEnter(Home)} />
          <Route exact path="/home/about" render={() => onEnter(About)} />
          <Route exact path="/home/echarts" render={() => onEnter(Echarts)} />
          <Route exact path="/home/form" render={() => onEnter(FormTable)} />
          <Route component={NotFound} />
        </Switch>
      </Suspense>
    </ErrorBoundary>
  )
}
Example #6
Source File: index.tsx    From next-plausible with MIT License 6 votes vote down vote up
export function usePlausible<E extends Events = any>() {
  return useCallback(function <N extends keyof E>(
    eventName: N,
    ...rest: EventOptionsTuple<E[N]>
  ) {
    return (window as any).plausible?.(eventName, rest[0])
  },
  [])
}
Example #7
Source File: index.ts    From react-useStateRef with MIT License 6 votes vote down vote up
useStateRef: UseStateRef = <S>(initialState?: S | (() => S)) => {
  const [state, setState] = useState(initialState);
  const ref = useRef(state);

  const dispatch: typeof setState = useCallback((setStateAction:any) => {
    ref.current = isFunction(setStateAction) ? setStateAction(ref.current) : setStateAction;

    setState(ref.current);
  }, []);

  return [state, dispatch, ref];
}
Example #8
Source File: deposit.ts    From anchor-web-app with Apache License 2.0 6 votes vote down vote up
export function useEarnDepositForm(): EarnDepositFormReturn {
  const { connected } = useAccount();

  const fixedFee = useFixedFee();

  const { uUST } = useBalances();

  const { taxRate, maxTax } = useUstTax();

  const [input, states] = useForm(
    earnDepositForm,
    {
      isConnected: connected,
      fixedGas: fixedFee,
      taxRate: taxRate,
      maxTaxUUSD: maxTax,
      userUUSTBalance: uUST,
    },
    () => ({ depositAmount: '' as UST }),
  );

  const updateDepositAmount = useCallback(
    (depositAmount: UST) => {
      input({
        depositAmount,
      });
    },
    [input],
  );

  return {
    ...states,
    updateDepositAmount,
  };
}
Example #9
Source File: BreadcrumbContext.tsx    From one-platform with MIT License 5 votes vote down vote up
BreadcrumbProvider = ({ children }: Props): JSX.Element => {
  // load it up
  const [dynamicCrumbs, setDynamicCrumbs] = useState<Record<string, Breadcrumb>>();
  const [breadcrumbs, setBreadcrumbs] = useState<Breadcrumb[]>([]);
  const { pathname } = useLocation();

  const handleDynamicCrumbs = useCallback((crumb: Record<string, Breadcrumb>): void => {
    // save recent visit to quick link
    setDynamicCrumbs((state) => ({ ...state, ...crumb }));
  }, []);

  useEffect(() => {
    const path = pathname.replace(config.baseURL, '');
    const matchedPath = (Object.keys(BREADCRUMB_USERFLOW) as ApiCatalogLinks[]).find((pattern) =>
      Boolean(matchPath(pattern, path))
    );
    if (matchedPath) {
      const crumbs = BREADCRUMB_USERFLOW[matchedPath]
        .map((userflow) =>
          LOOK_UP_TABLE?.[userflow] ? LOOK_UP_TABLE?.[userflow] : dynamicCrumbs?.[userflow]
        )
        .filter((crumb) => Boolean(crumb)) as Breadcrumb[];
      setBreadcrumbs(crumbs);
    } else {
      setBreadcrumbs([]);
    }
  }, [pathname, dynamicCrumbs]);

  /**
   * Context value to access glabally from anywhere
   * Memo to optimize at best
   */
  const value = useMemo(
    () => ({
      breadcrumbs,
      handleDynamicCrumbs,
    }),

    [breadcrumbs, handleDynamicCrumbs]
  );

  return <BreadcrumbContext.Provider value={value}>{children}</BreadcrumbContext.Provider>;
}
Example #10
Source File: MenuDefault.tsx    From react_admin with MIT License 5 votes vote down vote up
MenuDefault: React.FC<Iprops> = (props) => {
  const { collapsed } = props;

  /** 构建树结构 **/
  const makeTreeDom = useCallback((data): JSX.Element[] => {
    return data.map((v: MenuTypes) => {
      if (v.children) {
        return (
          <Menu.SubMenu
            key={v.key}
            title={
              <span>
                <Icon type={v.icon} />
                <span>{v.title}</span>
              </span>
            }
          >
            {makeTreeDom(v.children)}
          </Menu.SubMenu>
        );
      } else {
        return (
          <Menu.Item key={v.key}>
            <Link to={v.key}>
              <Icon type={v.icon} />
              <span>{v.title}</span>
            </Link>
          </Menu.Item>
        );
      }
    });
  }, []);

  /** 处理原始数据,将原始数据处理为层级关系 **/
  const treeDom: JSX.Element[] = useMemo(() => {
    const treeDom = makeTreeDom(MenuConfig);
    return treeDom;
  }, [MenuConfig]);

  return (
    <Sider trigger={null} collapsible collapsed={collapsed}>
      <div className="logo-home">
        <Link className="logo-link" to="/">
          <img src={require("src/assets/img/logo.f16d.png")} />
          <div className={collapsed ? "show" : ""}>TS + Hooks</div>
        </Link>
      </div>
      <Menu
        theme="dark"
        mode="inline"
        defaultSelectedKeys={[props.history.location.pathname]}
      >
        {treeDom}
      </Menu>
    </Sider>
  );
}
Example #11
Source File: CommentForm.tsx    From 3Speak-app with GNU General Public License v3.0 5 votes vote down vote up
export function CommentForm(props) {
  const [postingStatus, setPostingStatus] = useState(false)
  const commentBodyRef = useRef() as any
  const { parent_reflink } = props

  const postComment = useCallback(async () => {
    setPostingStatus(true)
    const [networkId, parent_author, parent_permlink] = (RefLink.parse(parent_reflink) as any).link
    const [reflink, finishOpt] = await AccountService.postComment({
      accountType: 'hive',
      body: commentBodyRef.current.value,
      parent_author,
      parent_permlink,
      username: 'sisy',
      permlink: `re-${parent_permlink}-${randomstring
        .generate({
          length: 8,
          charset: 'alphabetic',
        })
        .toLowerCase()}`,
      title: '',
      json_metadata: {},
    })
    if (typeof props.onCommentPost === 'function') {
      props.onCommentPost()
    }
    commentBodyRef.current.value = ''
    setPostingStatus(false)
  }, [parent_reflink])
  return (
    <>
      <textarea
        id="new-comment-body"
        className="form-control w-100"
        ref={commentBodyRef}
        placeholder="Comment here..."
        maxLength={25000}
      ></textarea>
      <button
        id="new-comment-btn"
        className="btn mt-1 btn-primary float-right"
        disabled={postingStatus}
        onClick={postComment}
      >
        {postingStatus ? <FontAwesomeIcon icon={faSpinner as any} spin /> : <span>Comment</span>}
      </button>
    </>
  )
}
Example #12
Source File: useDrag.ts    From overwolf-hooks with MIT License 5 votes vote down vote up
useDrag = (
  currentWindowID: string | null,
  { displayLog }: { displayLog?: boolean },
) => {
  const [owWindow, setOwWindow] = useState<string | null>(currentWindowID)
  const [
    initialMousePosition,
    setMousePosition,
  ] = useState<MousePostion | null>(null)
  const [isMouseDown, setMouseDown] = useState<boolean>(false)

  function onDragStart({
    clientX,
    clientY,
  }: React.MouseEvent<HTMLElement, MouseEvent>) {
    setMouseDown(true)
    setMousePosition({
      x: clientX,
      y: clientY,
    })
  }

  function isSignificantMouseMove({
    clientX,
    clientY,
  }: React.MouseEvent<HTMLElement, MouseEvent>) {
    if (!initialMousePosition) return false

    const diffX = Math.abs(clientX - initialMousePosition.x)
    const diffY = Math.abs(clientY - initialMousePosition.y)
    const isSignificant =
      diffX > SIGNIFICANT_MOUSE_MOVE_THRESHOLD ||
      diffY > SIGNIFICANT_MOUSE_MOVE_THRESHOLD

    return isSignificant
  }

  function onMouseMove(event: React.MouseEvent<HTMLElement, MouseEvent>) {
    if (!isMouseDown || !isSignificantMouseMove(event)) return
    setMouseDown(false)
    if (owWindow) {
      overwolf.windows.dragMove(owWindow)
      displayLog &&
        console.info(
          '[? overwolf-hooks][? useDrag][? onGameInfoUpdatedPayload] ',
          JSON.stringify(
            { clientX: event.clientX, clientY: event.clientY },
            null,
            2,
          ),
        )
    }
  }

  const setCurrentWindowID = useCallback((id: string) => {
    setOwWindow(id)
  }, [])

  return { setCurrentWindowID, onDragStart, onMouseMove } as const
}
Example #13
Source File: BackgroundWindow.tsx    From overwolf-modern-react-boilerplate with MIT License 5 votes vote down vote up
BackgroundWindow = () => {
  const [currentGame] = useRunningGame(OVERWOLF_HOOKS_OPTIONS)
  const [desktopWindow] = useWindow(DESKTOP, OVERWOLF_HOOKS_OPTIONS)
  const [ingameWindow] = useWindow(INGAME, OVERWOLF_HOOKS_OPTIONS)
  const [{ event, info }, setGameFeatures] = useGameEventProvider<
    HeathstoneOverwolfGEP.Info,
    HeathstoneOverwolfGEP.Event
  >(OVERWOLF_HOOKS_OPTIONS)
  const dispatch = useDispatch()

  const openStartupWindow = useCallback(() => {
    const gameRunning =
      currentGame?.id === Game.HearhtStone &&
      (currentGame?.gameRunning || currentGame?.gameChanged)
    const currentWindow = gameRunning ? ingameWindow : desktopWindow
    gameRunning && setGameFeatures(REQUIRED_FEATURES)

    currentWindow?.restore()
  }, [desktopWindow, ingameWindow, currentGame, setGameFeatures])

  useEffect(() => {
    event && dispatch(setEvent({ event }))
  }, [event, dispatch])

  useEffect(() => {
    info && dispatch(setInfo({ info }))
  }, [info, dispatch])

  useEffect(() => {
    openStartupWindow()
  }, [openStartupWindow])

  return <></>
}
Example #14
Source File: ProxyRenderer.tsx    From react-doc-viewer with Apache License 2.0 5 votes vote down vote up
ProxyRenderer: FC<{}> = () => {
  const { state, dispatch, CurrentRenderer } = useDocumentLoader();
  const { documents, documentLoading, currentDocument } = state;

  const size = useWindowSize();

  const containerRef = useCallback(
    (node) => {
      node && dispatch(setRendererRect(node?.getBoundingClientRect()));
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [size]
  );

  const Contents = () => {
    if (!documents.length) {
      return <div id="no-documents">{/* No Documents */}</div>;
    } else if (documentLoading) {
      return (
        <LoadingContainer id="loading-renderer" data-testid="loading-renderer">
          <LoadingIconContainer>
            <LoadingIcon color="#444" size={40} />
          </LoadingIconContainer>
        </LoadingContainer>
      );
    } else {
      if (CurrentRenderer) {
        return <CurrentRenderer mainState={state} />;
      } else if (CurrentRenderer === undefined) {
        return null;
      } else {
        return (
          <div id="no-renderer" data-testid="no-renderer">
            No Renderer for file type {currentDocument?.fileType}
            <DownloadButton
              id="no-renderer-download"
              href={currentDocument?.uri}
              download={currentDocument?.uri}
            >
              Download File
            </DownloadButton>
          </div>
        );
      }
    }
  };

  return (
    <Container id="proxy-renderer" ref={containerRef}>
      <Contents />
    </Container>
  );
}
Example #15
Source File: withdraw.ts    From anchor-web-app with Apache License 2.0 5 votes vote down vote up
export function useEarnWithdrawForm(): EarnWithdrawFormReturn {
  const { connected } = useAccount();

  const fixedFee = useFixedFee();

  const { uUST, uaUST } = useBalances();

  const { data } = useEarnEpochStatesQuery();

  const { totalDeposit } = useMemo(() => {
    return {
      totalDeposit: computeTotalDeposit(uaUST, data?.moneyMarketEpochState),
    };
  }, [data?.moneyMarketEpochState, uaUST]);

  const [input, states] = useForm(
    earnWithdrawForm,
    {
      isConnected: connected,
      fixedGas: fixedFee,
      userUUSTBalance: uUST,
      totalDeposit: totalDeposit,
    },
    () => ({ withdrawAmount: '' as UST }),
  );

  const updateWithdrawAmount = useCallback(
    (withdrawAmount: UST) => {
      input({
        withdrawAmount,
      });
    },
    [input],
  );

  return {
    ...states,
    updateWithdrawAmount,
  };
}