react#useMemo TypeScript Examples

The following examples show how to use react#useMemo. 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: useGetNamespaceList.tsx    From one-platform with MIT License 6 votes vote down vote up
useGetNamespaceList = ({
  limit = 10,
  search,
}: Props): UseQueryReturn<UseGetNamespaceListQuery> => {
  const searchCancelRef = useRef(new AbortController());
  const query = useQuery<UseGetNamespaceListQuery, Props>({
    gql: GET_NAMESPACE_LIST,
    variables: {
      limit,
      search,
    },
    pause: !search,
    context: useMemo(
      () => ({
        fetchOptions: () => {
          const token = window.OpAuthHelper.jwtToken;
          return {
            signal: searchCancelRef.current.signal,
            headers: { authorization: token ? `Bearer ${token}` : '' },
          };
        },
      }),
      []
    ),
  });

  useEffect(() => {
    searchCancelRef.current.abort();
  }, [search]);

  return query;
}
Example #2
Source File: MediaQueryProvider.tsx    From akashlytics with GNU General Public License v3.0 6 votes vote down vote up
export function MediaQueryProvider({ children }) {
  const phoneView = useMediaQuery(mediaQueries.phone);
  const mobileView = useMediaQuery(mediaQueries.mobile);
  const smallScreen = useMediaQuery(mediaQueries.small);
  const prefersReducedMotion = useMediaQuery(mediaQueries.prefersReducedMotion);
  const value = useMemo(() => ({ mobileView, prefersReducedMotion, smallScreen, phoneView }), [
    mobileView,
    prefersReducedMotion,
    smallScreen,
    phoneView,
  ]);

  return <MediaQueryContext.Provider value={value}>{children}</MediaQueryContext.Provider>;
}
Example #3
Source File: context.tsx    From anchor-web-app with Apache License 2.0 6 votes vote down vote up
export function AnchorWebappProvider({
  children,
  indexerApiEndpoints,
}: AnchorWebappProviderProps) {
  const { network } = useNetwork();

  //const { contractAddress } = useApp<AnchorContractAddress>();

  const states = useMemo<AnchorWebapp>(() => {
    return {
      indexerApiEndpoint: indexerApiEndpoints(network),
      //bAssetsVector: [contractAddress.cw20.bEth, contractAddress.cw20.bLuna],
    };
  }, [indexerApiEndpoints, network]);

  return (
    <AnchorWebappContext.Provider value={states}>
      {children}
    </AnchorWebappContext.Provider>
  );
}
Example #4
Source File: QRResImage.tsx    From react-qrbtf with MIT License 6 votes vote down vote up
QRResImage: SFC<QRResImageProps> = (props) => {
    const { qrcode, className, styles, otherColor } = props;

    const [gpl, setGPL] = useState<Array<JSX.Element>>([]);
    useMemo(() => {
        getGrayPointList(props, qrcode!.getModuleCount(), "#S-black", "#S-white").then(res => setGPL(res));
    }, [setGPL, props, qrcode])

    return (
        <svg className={className} style={styles.svg} width="100%" height="100%" viewBox={getViewBox(qrcode)} fill="white"
            xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink">
            <defs>
                <rect id="B-black" fill={otherColor} width={3.08} height={3.08} />
                <rect id="B-white" fill="white" width={3.08} height={3.08} />
                <rect id="S-black" fill={otherColor} width={1.02} height={1.02} />
                <rect id="S-white" fill="white" width={1.02} height={1.02} />
                <rect id="B" width={3.08} height={3.08} />
                <rect id="S" width={1.02} height={1.02} />
            </defs>
            {gpl.concat(listPoints(props))}
        </svg>
    );
}
Example #5
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 #6
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 #7
Source File: VideoTeaser.tsx    From 3Speak-app with GNU General Public License v3.0 5 votes vote down vote up
export function VideoTeaser(props: any) {
  const [video_info, setVideoInfo] = useState<any>({})
  const [thumbnail, setThumbnail] = useState('')
  const reflink = useMemo(() => {
    return Reflink.parse(props.reflink)
  }, [])

  useEffect(() => {
    const load = async () => {
      setVideoInfo(await AccountService.permalinkToVideoInfo(props.reflink))
      setThumbnail(await VideoService.getThumbnailURL(props.reflink))
    }

    void load()
  }, [])

  return (
    <div className="video-card-list">
      <div className="teaser_holder video-card-image">
        <div className="card-label">
          {(() => {
            const pattern = DateTime.compile('mm:ss')
            return DateTime.format(new Date(video_info.meta.duration * 1000), pattern)
          })()}
        </div>
        <a href={`#/watch/${props.reflink}`}>
          <img className="img-fluid bg-dark" src={thumbnail} alt="" />
        </a>
      </div>
      <span className="video-card-body">
        <div className="video-title">
          <a
            href={`#/watch/${props.reflink}`}
            style={{ textOverflow: 'ellipsis', overflow: 'nowrap' }}
          >
            {video_info.title}
          </a>
        </div>
        <div className="video-page">
          <a href={`#/user/${reflink.source.value}:${reflink.root}`}>{reflink.root}</a>
        </div>
        <div className="video-view">
          <FaEye /> Unknown views
          <span>
            <FaCalendarAlt />
            {(() => {
              if (video_info.creation) {
                const dateBest = convert(
                  (new Date(new Date().toUTCString()) as any) / 1 -
                    Date.parse(video_info.creation) / 1,
                )
                  .from('ms')
                  .toBest()
                if (Math.round(dateBest.val) >= 2) {
                  return `${Math.round(dateBest.val)} ${dateBest.plural} ago`
                } else {
                  return `${Math.round(dateBest.val)} ${dateBest.singular} ago`
                }
              }
            })()}
          </span>
        </div>
      </span>
    </div>
  )
}
Example #8
Source File: tooltip-transform-hook.ts    From react-circular-menu with Apache License 2.0 5 votes vote down vote up
useTooltipTransform = (
  wrapper: HTMLDivElement | null,
  tooltip: HTMLDivElement | null,
  placement: TooltipPlacement
): CSSProperties => {
  const calculateTransformStyle = (): CSSProperties => {
    if (!wrapper || !tooltip) {
      return {};
    }

    const wrapperBoundingRect = wrapper.getBoundingClientRect();
    const wrapperWidth = wrapperBoundingRect.right - wrapperBoundingRect.left;
    const wrapperHeight = wrapperBoundingRect.bottom - wrapperBoundingRect.top;

    const tooltipBoundingRect = tooltip.getBoundingClientRect();
    const tooltipWidth = tooltipBoundingRect.right - tooltipBoundingRect.left;
    const tooltipHeight = tooltipBoundingRect.bottom - tooltipBoundingRect.top;

    let left = wrapperBoundingRect.left + wrapperWidth / 2 - tooltipWidth / 2;
    let top = wrapperBoundingRect.top + wrapperHeight / 2 - tooltipHeight / 2;

    switch (placement) {
      case TooltipPlacement.Top:
        top = wrapperBoundingRect.top - tooltipHeight - tooltipPadding;
        break;
      case TooltipPlacement.Bottom:
        top = wrapperBoundingRect.bottom + tooltipPadding;
        break;
      case TooltipPlacement.Left:
        left = wrapperBoundingRect.left - tooltipWidth - tooltipPadding;
        break;
      case TooltipPlacement.Right:
        left = wrapperBoundingRect.right + tooltipPadding;
        break;
    }

    return {
      transform: `translate3d(${left}px, ${top}px, 0px)`,
    };
  };

  return useMemo(() => calculateTransformStyle(), [wrapper, tooltip]);
}
Example #9
Source File: GridVideo.tsx    From ReactNative-UIKit with MIT License 5 votes vote down vote up
GridVideo: React.FC = () => {
  const max = useContext(MaxUidContext);
  const min = useContext(MinUidContext);
  const {rtcProps, styleProps} = useContext(PropsContext);
  const users =
    rtcProps.role === ClientRole.Audience
      ? [...max, ...min].filter((user) => user.uid !== 'local')
      : [...max, ...min];
  let onLayout = (e: any) => {
    setDim([
      e.nativeEvent.layout.width,
      e.nativeEvent.layout.height,
      e.nativeEvent.layout.width > e.nativeEvent.layout.height,
    ]);
  };
  const [dim, setDim]: [
    [number, number, boolean],
    Dispatch<SetStateAction<[number, number, boolean]>>,
  ] = useState([
    Dimensions.get('window').width,
    Dimensions.get('window').height,
    Dimensions.get('window').width > Dimensions.get('window').height,
  ]);
  const isDesktop = dim[0] > dim[1] + 100;
  let {matrix, dims} = useMemo(
    () => layout(users.length, isDesktop),
    [users.length, isDesktop],
  );
  return (
    <View style={style.full} onLayout={onLayout}>
      {matrix.map((r, ridx) => (
        <View style={style.gridRow} key={ridx}>
          {r.map((c, cidx) => (
            <View style={style.col} key={cidx}>
              <View
                style={{
                  ...style.gridVideoContainerInner,
                  ...(styleProps?.gridVideoView as object),
                }}>
                {rtcProps.role === ClientRole.Audience &&
                users[ridx * dims.c + cidx].uid === 'local' ? null : (
                  <MaxVideoView
                    user={users[ridx * dims.c + cidx]}
                    key={users[ridx * dims.c + cidx].uid}
                  />
                )}
              </View>
            </View>
          ))}
        </View>
      ))}
    </View>
  );
}
Example #10
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,
  };
}
Example #11
Source File: CodeEditor.tsx    From firetable with Apache License 2.0 5 votes vote down vote up
export default function CodeEditor({
  onChange,
  value,
  height = 400,
  wrapperProps,
  disabled,
  editorOptions,
}: ICodeEditorProps) {
  const theme = useTheme();
  const [initialEditorValue] = useState(value ?? "");
  const { tableState } = useFiretableContext();
  const classes = useStyles();
  const monacoInstance = useMonaco();

  const editorRef = useRef<any>();

  function handleEditorDidMount(_, editor) {
    editorRef.current = editor;
  }

  const themeTransformer = (theme: string) => {
    switch (theme) {
      case "dark":
        return "vs-dark";
      default:
        return theme;
    }
  };

  useMemo(async () => {
    if (!monacoInstance) {
      // useMonaco returns a monaco instance but initialisation is done asynchronously
      // dont execute the logic until the instance is initialised
      return;
    }

    try {
      monacoInstance.languages.typescript.javascriptDefaults.setDiagnosticsOptions(
        {
          noSemanticValidation: true,
          noSyntaxValidation: false,
        }
      );
      // compiler options
      monacoInstance.languages.typescript.javascriptDefaults.setCompilerOptions(
        {
          target: monacoInstance.languages.typescript.ScriptTarget.ES5,
          allowNonTsExtensions: true,
        }
      );
    } catch (error) {
      console.error(
        "An error occurred during initialization of Monaco: ",
        error
      );
    }
  }, [tableState?.columns]);

  return (
    <div
      {...wrapperProps}
      className={clsx(classes.editorWrapper, wrapperProps?.className)}
    >
      <Editor
        theme={themeTransformer(theme.palette.type)}
        height={height}
        onMount={handleEditorDidMount}
        language="javascript"
        value={initialEditorValue}
        options={{
          readOnly: disabled,
          fontFamily: theme.typography.fontFamilyMono,
          ...editorOptions,
        }}
        onChange={onChange as any}
      />
    </div>
  );
}
Example #12
Source File: SegmentsTable.tsx    From abacus with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Renders the segments of a particular type.
 *
 * @param resolvedSegmentAssignments - The segment assignments with the
 *   segment IDs resolved to the actual segment.
 * @param type - The segment type the segment assignments represent.
 */
function SegmentsTable({
  resolvedSegmentAssignments,
  type,
}: {
  resolvedSegmentAssignments: {
    segment: Segment
    isExcluded: boolean
  }[]
  type: SegmentType
}): JSX.Element {
  const sortedResolvedSegmentAssignments = useMemo(
    () => _.orderBy(resolvedSegmentAssignments, [_.property('segment.name')]),
    [resolvedSegmentAssignments],
  )
  const classes = useStyles()
  return (
    <Table className={classes.root}>
      <TableHead>
        <TableRow>
          <TableCell component='th' variant='head'>
            {SegmentTypeToHeading[type]}
          </TableCell>
        </TableRow>
      </TableHead>
      <TableBody>
        {resolvedSegmentAssignments.length === 0 ? (
          <TableRow>
            <TableCell className={classes.monospace}>
              All {type === SegmentType.Country ? 'countries' : 'locales'} included
            </TableCell>
          </TableRow>
        ) : (
          sortedResolvedSegmentAssignments.map(
            (resolvedSegmentAssignment) =>
              resolvedSegmentAssignment.segment && (
                <TableRow key={resolvedSegmentAssignment.segment.segmentId}>
                  <TableCell className={classes.monospace}>
                    {resolvedSegmentAssignment.segment.name}{' '}
                    {resolvedSegmentAssignment.isExcluded && <Attribute name='excluded' />}
                  </TableCell>
                </TableRow>
              ),
          )
        )}
      </TableBody>
    </Table>
  )
}
Example #13
Source File: App.tsx    From react-final-table with MIT License 5 votes vote down vote up
function App() {
  const memoColumns = useMemo(() => columns, []);
  const memoData = useMemo(() => data, []);

  const { headers, rows, selectRow, selectedRows } = useTable(
    memoColumns,
    memoData,
    {
      selectable: true,
    }
  );


  return (
    <>
      <table>
        <thead>
          <tr>
            <th></th>
            {headers.map((header, idx) => (
              <th key={idx}>{header.label}</th>
            ))}
          </tr>
        </thead>
        <tbody>
          {rows.map((row, idx) => (
            <tr key={idx}>
              <td>
                <input
                  type="checkbox"
                  onChange={() => {
                    selectRow(row.id);
                  }}
                />
              </td>
              {row.cells.map((cell, idx) => (
                <td key={idx}>{cell.render()}</td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
      <pre>
        <code>{JSON.stringify(selectedRows)}</code>
      </pre>
      <h2>Pagination</h2>
      <PaginationTable />
    </>
  );
}
Example #14
Source File: common.tsx    From firecms with MIT License 5 votes vote down vote up
export function useColumnIds<M>(collection: EntityCollection<M>, resolvedSchema:ResolvedEntitySchema<M>, includeSubcollections: boolean): string[] {

    return useMemo(() => {
        const initialDisplayedProperties = collection.properties;
        const excludedProperties = collection.excludedProperties;
        const additionalColumns = collection.additionalColumns ?? [];
        const subCollections: EntityCollection[] = collection.subcollections ?? [];

        const properties:Properties = resolvedSchema.properties;

        const hiddenColumnIds: string[] = Object.entries(properties)
            .filter(([_, property]) => {
                return property.disabled && typeof property.disabled === "object" && property.disabled.hidden;
            })
            .map(([propertyKey, _]) => propertyKey);

        const columnIds: string[] = [
            ...Object.keys(collection.schema.properties) as string[],
            ...additionalColumns.map((column) => column.id)
        ];

        let result: string[];
        if (initialDisplayedProperties) {
            result = initialDisplayedProperties
                .map((p) => {
                    return columnIds.find(id => id === p);
                }).filter(c => !!c) as string[];
        } else if (excludedProperties) {
            result = columnIds
                .filter(id => !(excludedProperties as string[]).includes(id));
        } else {
            result = columnIds.filter((columnId) => !hiddenColumnIds.includes(columnId));
        }

        if (includeSubcollections) {
            const subCollectionIds = subCollections
                .map((collection) => getSubcollectionColumnId(collection))
                .filter((subColId) => excludedProperties ? !excludedProperties?.includes(subColId) : true);
            result.push(...subCollectionIds.filter((subColId) => !result.includes(subColId)));
        }

        return result;

    }, [collection.properties, collection.excludedProperties, collection.additionalColumns, collection.subcollections, collection.schema.properties, resolvedSchema.properties, includeSubcollections]);
}
Example #15
Source File: Sidebar.tsx    From one-platform with MIT License 4 votes vote down vote up
Sidebar = ({ isOpen }: Props): JSX.Element => {
  const { pathname, search } = useLocation();
  const url = pathname.replace(config.baseURL, '');
  const { logs, quickLink } = useRecentVisit();
  const userInfo = opcBase.auth?.getUserInfo();
  const navLinks = useMemo(() => navMenuLinks(userInfo?.rhatUUID || ''), [userInfo?.rhatUUID]);

  const getToolImage = useCallback((tool: string) => {
    if (tool === 'playground') return `${config.baseURL}/images/gql-playground-logo.svg`;
    if (tool === 'redoc') return `${config.baseURL}/images/redoc-logo.png`;
    return `${config.baseURL}/images/${tool}-logo.svg`;
  }, []);

  const isQuickLinkActive = logs?.[0]?.url === pathname;
  const isQuickLinkGraphql = logs?.[0]?.tool !== 'swagger' && logs?.[0]?.tool !== 'redoc';

  const getQuickLinks = useCallback(() => {
    if (isQuickLinkActive) {
      const links = isQuickLinkGraphql ? graphqlQuickLinks : restQuickLinks;
      return (
        <NavGroup title={`${quickLink?.name} quick links`}>
          {links.map(({ url: path, label, img }) => (
            <NavItem key={`quick-link-${label}`}>
              <Link
                to={path
                  .replace(':id', quickLink?.id || '')
                  .replace(':envSlug', quickLink?.envSlug || '')}
              >
                <Split>
                  <SplitItem className="pf-u-mr-sm pf-u-display-flex pf-u-align-items-center">
                    <img
                      src={`${config.baseURL}/images/${img}`}
                      width="16px"
                      alt="quick link icon"
                    />
                  </SplitItem>
                  <SplitItem>{label}</SplitItem>
                </Split>
              </Link>
            </NavItem>
          ))}
        </NavGroup>
      );
    }
    return null;
  }, [isQuickLinkActive, isQuickLinkGraphql, quickLink?.id, quickLink?.name, quickLink?.envSlug]);

  return (
    <PageSidebar
      theme="light"
      isNavOpen={isOpen}
      className={styles['app-layout--sidebar']}
      nav={
        <Stack hasGutter>
          <StackItem isFilled>
            <Nav theme="light">
              <NavList className="pf-u-mb-lg">
                {navLinks.map(({ url: pattern, label, icon: Icon }, index) => (
                  <NavItem
                    key={`nav-menu-link:${label}`}
                    id="home-link"
                    itemId={index}
                    isActive={pattern === url + search}
                  >
                    <Link to={pattern}>
                      <Split>
                        <SplitItem className="pf-u-mr-sm">
                          <Icon />
                        </SplitItem>
                        <SplitItem>{label}</SplitItem>
                      </Split>
                    </Link>
                  </NavItem>
                ))}
              </NavList>
              {getQuickLinks()}
              <NavGroup title="Recent visited">
                {logs?.map(({ title, url: toolUrl, tool }) => (
                  <NavItem key={`nav-item-${toolUrl}`}>
                    <Link to={toolUrl.replace(config.baseURL, '/')}>
                      <Split hasGutter className="pf-u-align-items-center">
                        <SplitItem>
                          <img src={getToolImage(tool)} style={{ height: '24px' }} alt="swagger" />
                        </SplitItem>
                        <SplitItem>
                          <Title headingLevel="h6">{title}</Title>
                          <Text component={TextVariants.small} className="capitalize">
                            {tool}
                          </Text>
                        </SplitItem>
                      </Split>
                    </Link>
                  </NavItem>
                ))}
              </NavGroup>
            </Nav>
          </StackItem>
          <StackItem>
            <Footer />
          </StackItem>
        </Stack>
      }
    />
  );
}