react#useMemo JavaScript 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: Application.js    From about-1hive with GNU General Public License v3.0 6 votes vote down vote up
export default function Provider({ children }) {
  const [state, dispatch] = useReducer(reducer, INITIAL_STATE)

  const updateDarkMode = useCallback(mode => {
    dispatch({
      type: UPDATE_DARKMODE,
      payload: {
        mode
      }
    })
  }, [])

  return (
    <ApplicationContext.Provider value={useMemo(() => [state, { updateDarkMode }], [state, updateDarkMode])}>
      {children}
    </ApplicationContext.Provider>
  )
}
Example #2
Source File: MySalary.js    From payroll-app with GNU Affero General Public License v3.0 6 votes vote down vote up
function Split({ children }) {
  const { layoutName } = useLayout()

  const columns = useMemo(() => {
    if (layoutName === 'small') {
      return '1fr'
    }

    if (layoutName === 'medium') {
      return 'repeat(auto-fit, minmax(300px, auto))'
    }

    return '1fr 1fr 2fr'
  }, [layoutName])

  return (
    <div
      css={`
        display: grid;
        grid-template-columns: ${columns};
        grid-gap: ${2 * GU}px;
        margin-bottom: ${2 * GU}px;
        ${layoutName === 'medium' &&
          `& > :last-child {
            grid-column: span 2;
          }`}
      `}
    >
      {children}
    </div>
  )
}
Example #3
Source File: useFetchPoolInfo.js    From tulip-frontend with GNU Affero General Public License v3.0 6 votes vote down vote up
useFetchPoolInfo = () => {
  const [poolInfo, setPoolInfo] = useState(null)
  const {
    _web3ReactContext: { chainId },
  } = useWallet()

  useEffect(() => {
    const loadPoolInfo = async () => {
      const pInfo = await tulipData.farm.info({ chain_id: chainId })
      setPoolInfo(pInfo)
    }
    loadPoolInfo()
  }, [chainId])
  const info = useMemo(() => poolInfo, [poolInfo])
  return info
}
Example #4
Source File: Allowances.js    From uniswap-v1-frontend with GNU General Public License v3.0 6 votes vote down vote up
export default function Provider({ children }) {
  const [state, dispatch] = useReducer(reducer, {})

  const update = useCallback((networkId, address, tokenAddress, spenderAddress, value, blockNumber) => {
    dispatch({ type: UPDATE, payload: { networkId, address, tokenAddress, spenderAddress, value, blockNumber } })
  }, [])

  return (
    <AllowancesContext.Provider value={useMemo(() => [state, { update }], [state, update])}>
      {children}
    </AllowancesContext.Provider>
  )
}
Example #5
Source File: dataProvider.js    From acy-dex-interface with MIT License 6 votes vote down vote up
export function useCoingeckoPrices(symbol, { from = FIRST_DATE_TS } = {}) {
  // token ids https://api.coingecko.com/api/v3/coins
  const _symbol = {
    BTC: 'bitcoin',
    ETH: 'ethereum',
    LINK: 'chainlink',
    UNI: 'uniswap',
    AVAX: 'avalanche-2'
  }[symbol]

  const now = Date.now() / 1000
  const days = Math.ceil(now / 86400) - Math.ceil(from / 86400) - 1

  const url = `https://api.coingecko.com/api/v3/coins/${_symbol}/market_chart?vs_currency=usd&days=${days}&interval=daily`

  const [res, loading, error] = useRequest(url)

  const data = useMemo(() => {
    if (!res || res.length === 0) {
      return null
    }

    const ret = res.prices.map(item => {
      // -1 is for shifting to previous day
      // because CG uses first price of the day, but for ALP we store last price of the day
      const timestamp = item[0] - 1
      const groupTs = parseInt(timestamp / 1000 / 86400) * 86400
      return {
        timestamp: groupTs,
        value: item[1]
      }
    })
    return ret
  }, [res])

  return [data, loading, error]
}
Example #6
Source File: Provider.js    From Path-Finding-Visualizer with MIT License 6 votes vote down vote up
function Provider(_ref) {
  var store = _ref.store,
      context = _ref.context,
      children = _ref.children;
  var contextValue = useMemo(function () {
    var subscription = new Subscription(store);
    subscription.onStateChange = subscription.notifyNestedSubs;
    return {
      store: store,
      subscription: subscription
    };
  }, [store]);
  var previousState = useMemo(function () {
    return store.getState();
  }, [store]);
  useEffect(function () {
    var subscription = contextValue.subscription;
    subscription.trySubscribe();

    if (previousState !== store.getState()) {
      subscription.notifyNestedSubs();
    }

    return function () {
      subscription.tryUnsubscribe();
      subscription.onStateChange = null;
    };
  }, [contextValue, previousState]);
  var Context = context || ReactReduxContext;
  return React.createElement(Context.Provider, {
    value: contextValue
  }, children);
}
Example #7
Source File: useNotifications.js    From e-Pola with MIT License 6 votes vote down vote up
/**
 * React hook for access to notifications. Returns
 * showSuccess, showError and showMessage
 * @returns {object} Notification actions
 */
export default function useNotifications() {
  const dispatch = useDispatch()
  return useMemo(() => {
    return bindActionCreators(actions, dispatch)
  }, [dispatch])
}
Example #8
Source File: App.js    From react-pixel-art-maker with MIT License 6 votes vote down vote up
function App() {
  const [cells, setCells] = useState(initialCells);
  const [currentColor, setCurrentColor] = useState('#56BC58');
  const classes = useStyles();
  const colorSwatch = useMemo(
    () => [
      ...new Set(cells.filter((cell) => cell.on).map((cell) => cell.color)),
    ],
    [cells]
  );
  const chatString = useMemo(
    () => cells.map((cell) => cell.color.slice(1)).join(','),
    [cells]
  );
  return (
    <div className={classes.app}>
      <ColorPicker currentColor={currentColor} onSetColor={setCurrentColor} />
      <div className={classes.colorSwatchContainer}>
        {colorSwatch.map((color) => (
          <div
            key={color}
            onClick={() => setCurrentColor(color)}
            className={classes.colorSwatch}
            style={{ background: color }}
          />
        ))}
      </div>
      <Grid cells={cells} setCells={setCells} currentColor={currentColor} />
      <p className={classes.chatString}>
        {/* eslint-disable-next-line */}
        !rgb
        {' '}
        {chatString}
      </p>
    </div>
  );
}
Example #9
Source File: Effects.js    From 3d-react-demo with MIT License 6 votes vote down vote up
export default function Effects() {
  const composer = useRef();
  const { scene, gl, size, camera } = useThree();
  const aspect = useMemo(() => new THREE.Vector2(size.width, size.height), [
    size,
  ]);
  useEffect(() => void composer.current.setSize(size.width, size.height), [
    size,
  ]);
  useFrame(() => composer.current.render(), 1);

  const bloom = {
    resolution: aspect,
    strength: 0.6,
    radius: 0.01,
    threshold: 0.4,
  };

  return (
    <effectComposer ref={composer} args={[gl]}>
      <renderPass attachArray="passes" scene={scene} camera={camera} />

      <unrealBloomPass
        attachArray="passes"
        args={[bloom.resolution, bloom.strength, bloom.radius, bloom.threshold]}
      />
      <shaderPass
        attachArray="passes"
        args={[FXAAShader]}
        material-uniforms-resolution-value={[1 / size.width, 1 / size.height]}
        renderToScreen
      />
    </effectComposer>
  );
}
Example #10
Source File: useZeecretTeam.js    From Legacy with Mozilla Public License 2.0 6 votes vote down vote up
export default function useZeecretTeam(username, nav) {
  const userBookmarks = useSelector(i => i.userBookmarks);
  const navCached = useMemo(()=>nav)
  const { data, status } = (navCached ? useAPIRequestWithoutNav : useAPIRequest)(
    (!username || userBookmarks.some(i => i.username === username)) ? {
      endpoint: "competition/users/v2",
      data: {
        users: userBookmarks.map(i => i.username).join(',')
      },
      cuppazee: true
    } : {
        endpoint: "competition/users/v2",
        data: {
          users: username
        },
        cuppazee: true
      }, true)
  return {
    data: username ? data?.[username] : data,
    status: status
  }
}
Example #11
Source File: Checkbox.js    From beautiful-react-ui with MIT License 6 votes vote down vote up
Checkbox = (props) => {
  const { value, onChange, color, helpText, className, CheckIconRender, style, ...rest } = props;
  const classList = useMemo(() => classNames('bi bi-checkbox', `bi-checkbox-${color}`, {
    checked: !!value,
    disabled: rest.disabled,
  }, className), [color, value, rest.disabled]);

  const onClick = !rest.disabled ? useCallback(makeCallback(onChange, !value), [onChange, value]) : undefined;
  const onKeyUp = !rest.disabled ? useCallback(makeKeyboardCallback(onChange, !value), [onChange, value]) : undefined;

  return (
    // eslint-disable-next-line max-len
    <div className={classList} onClick={onClick} onKeyUp={onKeyUp} tabIndex={0} role="checkbox" aria-checked={value} style={style}>
      <input type="checkbox" value={value} {...rest} />
      <CheckIconRender checked={!!value} color={color} />
      {helpText && <HelpText text={helpText} />}
    </div>

  );
}
Example #12
Source File: DownloadPage.js    From Website with MIT License 6 votes vote down vote up
DownloadPage = () => {
	const os = useMemo(getOS, []);
	return (
		<div className="download-page">
			<div className="left">
				<Feature
					title="DisStreamChat Chat Client"
					subtitle="All your stream chats in one place"
					body="Keeping track of your stream can be really difficult, especially if you are streaming cross platform and have large discord
					community. DisStreamChat allows you have all your chats in one place so you can easily view and moderate the chat."
					images={[
						"https://panels-images.twitch.tv/panel-40229165-image-1b8f110f-2370-4af4-9610-a6bcb9ee8872",
					]}
				></Feature>
			</div>
			<div className="right downloads">
				<OsDownloadPage os={os} />
			</div>
		</div>
	);
}
Example #13
Source File: useIsMobile.js    From react-context-responsive with MIT License 6 votes vote down vote up
useIsMobile = () => {
    const { isCalculated, lessThan, mobileBreakpoint } = useResponsive();
    const isMobile = lessThan[mobileBreakpoint];

    return useMemo(() => ({ isMobile, isCalculated }), [
        isMobile,
        isCalculated,
    ]);
}
Example #14
Source File: useLocationHash.js    From utahjs-gatsby with BSD Zero Clause License 6 votes vote down vote up
export default function useLocationHash(deps = []) {
  return useMemo(() => {
    if (typeof window === 'undefined') {
      return {};
    }
    const hash = {};
    const params = new URLSearchParams(window.location.hash.slice(1));
    for (const [key, value] of params) {
      hash[key] = value;
    }
    return hash;
  }, deps);
}
Example #15
Source File: index.js    From website with MIT License 6 votes vote down vote up
CreateDonationPage = ({ mode, donation }) => {
  const [state, dispatch] = useReducer(reducer, initialState);

  // prevent re-rendering
  const contextValue = useMemo(() => {
    return { state, dispatch };
  }, [state, dispatch]);

  return (
    <DonationContext.Provider value={contextValue}>
      <Container>
        <HeadingWrapper>
          <Stack spacing="loose">
            <Heading>What are you donating today?</Heading>
            <Alert icon title="Some additional information" type="info">
              As a donor, you are <b>encouraged</b> to cover the delivery cost (if there is) to the specified location.
              This is to encourage donations of good and usable items to the beneficiaries or organizations.
            </Alert>
          </Stack>
        </HeadingWrapper>

        <Wrapper>
          <CreateDonationPanel mode={mode} donation={donation} />
        </Wrapper>
      </Container>
    </DonationContext.Provider>
  );
}
Example #16
Source File: style.js    From Queen with MIT License 6 votes vote down vote up
StyleProvider = ({ children }) => {
  // const prefersDarkMode = useMediaQuery('(prefers-color-scheme: dark)');

  const theme = useMemo(
    () =>
      createMuiTheme({
        palette: {
          // type: prefersDarkMode ? 'dark' : 'light',
          primary: {
            main: '#085394',
          },
          secondary: {
            main: '#FFFFFF',
          },
          declarations: {
            main: '#085394',
            help: 'black',
          },
          background: {
            default: '#eeeeee',
          },
        },
        breakpoints: {
          values: {
            xs: 0,
            sm: 460,
            md: 750,
            lg: 875,
            xl: 1200,
          },
        },
      }),
    []
  );

  return <ThemeProvider theme={theme}>{children}</ThemeProvider>;
}
Example #17
Source File: Accordion.js    From basis with MIT License 6 votes vote down vote up
function Item(props) {
  const theme = useTheme();
  const { itemGap } = useAccordion();
  const [headerId] = useState(() => `accordion-item-header-${nanoid()}`);
  const [contentId] = useState(() => `accordion-item-content-${nanoid()}`);
  const mergedProps = mergeProps(
    props,
    DEFAULT_ITEM_PROPS,
    {},
    {
      initiallyOpen: (initiallyOpen) => typeof initiallyOpen === "boolean",
    }
  );
  const { initiallyOpen, children, testId } = mergedProps;
  const [isOpen, setIsOpen] = useState(initiallyOpen);
  const toggleAccordionItem = useCallback(() => {
    setIsOpen((isOpen) => !isOpen);
  }, []);
  const accordionItemInfo = useMemo(
    () => ({
      headerId,
      contentId,
      isOpen,
      toggleAccordionItem,
    }),
    [headerId, contentId, isOpen, toggleAccordionItem]
  );

  return (
    <AccordionItemProvider value={accordionItemInfo}>
      <div
        css={theme.accordion.getCSS({ targetElement: "item", itemGap })}
        data-testid={testId}
      >
        {children}
      </div>
    </AccordionItemProvider>
  );
}
Example #18
Source File: CloudProvider.js    From lens-extension-cc with MIT License 6 votes vote down vote up
CloudProvider = function (props) {
  if (!_initialized) {
    IpcRenderer.getInstance().listen(
      ipcEvents.broadcast.CLOUD_STATUS_CHANGE,
      _handleCloudStatusChange
    );
    IpcRenderer.getInstance().listen(
      ipcEvents.broadcast.CLOUD_LOADED_CHANGE,
      _handleCloudLoadedChange
    );
    IpcRenderer.getInstance().listen(
      ipcEvents.broadcast.CLOUD_FETCHING_CHANGE,
      _handleCloudFetchingChange
    );
    _initialized = true;
  }

  // NOTE: since the state is passed directly (by reference) into the context
  //  returned by the provider, even the initial state should be a clone of the
  //  `store` so that we consistently return a `state` property (in the context)
  //  that is a shallow clone of the `store`
  const [state, setState] = useState(pr.clone());
  const value = useMemo(() => [state, setState], [state]);

  pr.setState = setState;

  // @see https://mobx.js.org/reactions.html#autorun
  // NOTE: I have no idea why, but using a reaction() like we do in the SyncStore
  //  on MAIN (which works fine there) is DOA here on RENDERER: the reaction is
  //  never called except on first-run; only autorun() works
  autorun(_handleAutoRun);

  return <CloudContext.Provider value={value} {...props} />;
}
Example #19
Source File: AuthProvider.js    From gatsby-apollo-wpgraphql-jwt-starter with MIT License 6 votes vote down vote up
AuthProvider = ({ children }) => {
  const [loginUser, { data: loginData }] = useMutation(LOGIN_USER)
  const [userData, setUserData] = useState(null)

  const providerValue = useMemo(() => (
    {
      loginUser: ({ username, password }) => loginUser({
        variables: {
          input: {
            clientMutationId: uuid(),
            username: username,
            password: password,
          },
        },
      }).then((response) => {
        console.log("Response", response)
        // console.log("Data", data)
        const { login } = response.data
        const user = (login && login.user) ? login.user : {}

        setRefreshToken(user, () => navigate("/dashboard/"))
      }),
      loginData: loginData,
      userData: userData,
      setUserData: setUserData
    }
  ), [loginUser, loginData, userData, setUserData])


  return (
    <AuthContext.Provider value={providerValue}>
      {children}
    </AuthContext.Provider>
  )
}
Example #20
Source File: highlight.js    From Nextjs-ja-translation-docs with MIT License 6 votes vote down vote up
export default function Highlight({ children, language, ...props }) {
  const highlighted = useMemo(() => {
    const html = children;
    return hljs.highlightAuto(html, ['javascript']).value;
  }, [children]);

  return (
    <pre>
      {/* eslint-disable react/no-danger */}
      <code
        {...props}
        dangerouslySetInnerHTML={{
          __html: highlighted
        }}
      />
    </pre>
  );
}
Example #21
Source File: index.js    From course-manager with MIT License 6 votes vote down vote up
export default function ThemeConfig({ children }) {
  const themeOptions = useMemo(
    () => ({
      palette,
      shape,
      typography,
      breakpoints,
      shadows,
      customShadows
    }),
    []
  );

  const theme = createTheme(themeOptions);
  theme.components = componentsOverride(theme);

  return (
    <StyledEngineProvider injectFirst>
      <ThemeProvider theme={theme}>
        <CssBaseline />
        <GlobalStyles />
        {children}
      </ThemeProvider>
    </StyledEngineProvider>
  );
}
Example #22
Source File: Products.js    From dshop with MIT License 6 votes vote down vote up
AllProducts = () => {
  const { collections } = useCollections()
  const match = useRouteMatch('/products/:collection')

  const collectionId = get(match, 'params.collection')

  const collectionTitle = useMemo(() => {
    if (!collectionId) return null

    const collection = collections.find((c) => c.id == collectionId)

    if (collection) return collection.title

    return null
  }, [collectionId, collections])

  return (
    <>
      <div className="container">
        {!collectionTitle ? null : (
          <div className="text-center text-4xl font-medium mb-24 font-header">
            {collectionTitle}
          </div>
        )}
        <Products />
      </div>
    </>
  )
}
Example #23
Source File: useFilteredPayments.js    From payroll-app with GNU Affero General Public License v3.0 5 votes vote down vote up
function useFilteredPayments() {
  const { payments = [] } = useAppState()
  const connectedAccount = useConnectedAccount()

  const [selectedDateRange, setSelectedDateRange] = useState(
    UNSELECTED_DATE_RANGE_FILTER
  )
  const [selectedToken, setSelectedToken] = useState(UNSELECTED_TOKEN_FILTER)

  const handleSelectedDateRangeChange = useCallback(range => {
    setSelectedDateRange(range)
  }, [])

  const handleTokenChange = useCallback(index => {
    const tokenIndex = index === 0 ? UNSELECTED_TOKEN_FILTER : index
    setSelectedToken(tokenIndex)
  }, [])

  const handleClearFilters = useCallback(() => {
    setSelectedDateRange(UNSELECTED_DATE_RANGE_FILTER)
  }, [])

  const currentEmployeePayments = useMemo(
    () =>
      payments.filter(({ accountAddress }) =>
        addressesEqual(accountAddress, connectedAccount)
      ),
    [connectedAccount, payments]
  )

  const tokens = ['All', ...new Set(payments.map(({ token }) => token.symbol))]

  const filteredPayments = useMemo(
    () =>
      currentEmployeePayments.filter(({ date }) => {
        if (
          selectedDateRange.start &&
          selectedDateRange.end &&
          !dateIsBetween(date, selectedDateRange.start, selectedDateRange.end)
        ) {
          return false
        }
        return true
      }),
    [currentEmployeePayments, selectedDateRange]
  )

  const emptyResultsViaFilters =
    filteredPayments.length === 0 &&
    (selectedToken > 0 || Boolean(selectedDateRange.start))

  return {
    currentEmployeePayments,
    emptyResultsViaFilters,
    filteredPayments,
    handleClearFilters,
    handleSelectedDateRangeChange,
    handleTokenChange,
    selectedDateRange,
    selectedToken,
    tokens,
  }
}
Example #24
Source File: useAirdrop.js    From tulip-frontend with GNU Affero General Public License v3.0 5 votes vote down vote up
export function useClaim() {
  const [working, setWorking] = useState(false)
  const [txHash, setTxHash] = useState('')
  const {
    account,
    status,
    _web3ReactContext: { chainId },
  } = useWallet()
  const [unclaimed, setUnclaimed] = useState(0)
  const [available, setAvailable] = useState(0)
  const [balance, setBalance] = useState(0)
  const networks = getNetworkConfig(chainId)

  const contract = useContract(networks.StreamedAirdropper, StreamedAirdropper)
  const tokenb = useContract(networks.xCombToken, ERC20)

  const claim = useMemo(() => {
    if (!account || status === 'disconnected') {
      return
    }

    return async () => {
      const trnHash = await contract.withdrawTo(account)
      if (trnHash) {
        setTxHash(trnHash)
        setWorking(true)
        await trnHash.wait()
      }
      setWorking(false)
    }
  }, [account, contract, status])

  useEffect(() => {
    if (!account || status === 'disconnected') {
      setAvailable(0)
      return
    }
    let cancelled = false
    const fetchAvailable = async () => {
      try {
        const tokens = await contract.pendingTokens(account)
        if (!cancelled && tokens) {
          setAvailable(utils.formatUnits(tokens).substring(0, 9))
        }

        return tokens
      } catch (err) {
        console.error(`Could not fetch airdrop data `, err)
      }
    }

    const fetchUnclaimedData = async () => {
      try {
        const result = await contract.vestingUsers(account)
        if (result.length > 0) {
          const remainingTokens = result[0]
          const tokenBalance = await tokenb.balanceOf(account)
          setBalance(utils.formatUnits(tokenBalance).substring(0, 9))

          const rTokens = utils.formatUnits(remainingTokens)
          if (rTokens) {
            setUnclaimed(parseFloat(rTokens).toFixed(4))
          }
        }
      } catch (err) {
        console.log(err)
      }
    }

    fetchAvailable()
    fetchUnclaimedData()
    return () => {
      cancelled = true
    }
  }, [account, status, working])

  return [balance, claim, available, unclaimed, txHash, working]
}
Example #25
Source File: Tokens.js    From uniswap-v1-frontend with GNU General Public License v3.0 5 votes vote down vote up
export function useAllTokenDetails() {
  const { chainId } = useWeb3React()

  const [state] = useTokensContext()

  return useMemo(() => ({ ...ETH, ...(safeAccess(state, [chainId]) || {}) }), [state, chainId])
}
Example #26
Source File: prices.js    From acy-dex-interface with MIT License 5 votes vote down vote up
export function useChartPrices(chainId, symbol, isStable, period, currentAveragePrice) {
  const swrKey = (!isStable && symbol) ? ['getChartCandles', chainId, symbol, period] : null
  let { data: prices, mutate: updatePrices } = useSWR(swrKey, {
    fetcher: async (...args) => {
      try {
        console.log("swrKey: ", swrKey);
        // TODO: TESTING
        // chainId is fixed to be 56 for testing
        const res =  await getChartPricesFromStats(56, symbol, period);
        console.log("swrKey: ", swrKey, "fetched data: ", res);
        return res;
      } catch (ex) {
        console.warn('getChartPricesFromBackend failed: ', ex)
        // console.warn('Switching to graph chainlink data')
      //   try {
      //     return await getChainlinkChartPricesFromGraph(symbol, period)
      //   } catch (ex2) {
      //     console.warn('getChainlinkChartPricesFromGraph failed')
      //     console.warn(ex2)
      //     return []
      //   }
      }
    },
    dedupingInterval: 60000,
    focusThrottleInterval: 60000 * 10
  })

  const currentAveragePriceString = currentAveragePrice && currentAveragePrice.toString()
  const retPrices = useMemo(() => {
    if (isStable) {
      return getStablePriceData(period)
    }

    if (!prices) {
      return []
    }

    let _prices = [...prices]
    if (currentAveragePriceString && prices.length) {
      _prices = appendCurrentAveragePrice(_prices, BigNumber.from(currentAveragePriceString), period)
    }

    return fillGaps(_prices, CHART_PERIODS[period])
  }, [prices, isStable, currentAveragePriceString, period])

  return [retPrices, updatePrices]
}
Example #27
Source File: useSelector.js    From Path-Finding-Visualizer with MIT License 5 votes vote down vote up
function useSelectorWithStoreAndSubscription(selector, equalityFn, store, contextSub) {
  var _useReducer = useReducer(function (s) {
    return s + 1;
  }, 0),
      forceRender = _useReducer[1];

  var subscription = useMemo(function () {
    return new Subscription(store, contextSub);
  }, [store, contextSub]);
  var latestSubscriptionCallbackError = useRef();
  var latestSelector = useRef();
  var latestSelectedState = useRef();
  var selectedState;

  try {
    if (selector !== latestSelector.current || latestSubscriptionCallbackError.current) {
      selectedState = selector(store.getState());
    } else {
      selectedState = latestSelectedState.current;
    }
  } catch (err) {
    if (latestSubscriptionCallbackError.current) {
      err.message += "\nThe error may be correlated with this previous error:\n" + latestSubscriptionCallbackError.current.stack + "\n\n";
    }

    throw err;
  }

  useIsomorphicLayoutEffect(function () {
    latestSelector.current = selector;
    latestSelectedState.current = selectedState;
    latestSubscriptionCallbackError.current = undefined;
  });
  useIsomorphicLayoutEffect(function () {
    function checkForUpdates() {
      try {
        var newSelectedState = latestSelector.current(store.getState());

        if (equalityFn(newSelectedState, latestSelectedState.current)) {
          return;
        }

        latestSelectedState.current = newSelectedState;
      } catch (err) {
        // we ignore all errors here, since when the component
        // is re-rendered, the selectors are called again, and
        // will throw again, if neither props nor store state
        // changed
        latestSubscriptionCallbackError.current = err;
      }

      forceRender({});
    }

    subscription.onStateChange = checkForUpdates;
    subscription.trySubscribe();
    checkForUpdates();
    return function () {
      return subscription.tryUnsubscribe();
    };
  }, [store, subscription]);
  return selectedState;
}
Example #28
Source File: index.js    From website with Apache License 2.0 5 votes vote down vote up
addPer100kValues = (timeSeriesData, populationData) => {
  /**
   * Adds per 100k fields to the timeSeries data.
   */

  const crdtToAcsDict = {
    AIAN: 'aian',
    Asian: 'asian',
    Black: 'black',
    Hispanic: 'hisp',
    LatinX: 'hisp',
    NHPI: 'nhpi',
    NonHispanic: 'notHisp',
    Other: 'other',
    Total: 'total',
    Multiracial: 'twoOrMore',
    White: 'white',
    // todo handle other and unknown
  }

  const timeSeriesWithPer100k = useMemo(() => {
    const completeData = timeSeriesData

    timeSeriesData.forEach((day, dayIndex) => {
      // For each day...
      Object.keys(day).forEach(metricKey => {
        // For each metric on each day...
        if (day[metricKey] === null) {
          // Skip if the value is null
          return
        }
        const raceEthnicityGroup = removeMetricPrefix(metricKey)
        const groupAcsName = crdtToAcsDict[raceEthnicityGroup]

        if (groupAcsName === undefined) {
          return
        }

        const groupPopulation = populationData[groupAcsName]
        const perCapitaRate = day[metricKey] / groupPopulation
        const per100kRate = Math.round(perCapitaRate * 100000)

        const newMetricKey = `${metricKey}_per100k`

        completeData[dayIndex][newMetricKey] = per100kRate
      })
    })
    return completeData
  }, [timeSeriesData])

  return timeSeriesWithPer100k
}
Example #29
Source File: Reactions.jsx    From genshin with MIT License 5 votes vote down vote up
Reactions = () => {
  const dispatch = useDispatch();
  const [currentFocusElement, setCurrentFocusElement] = useState([]);

  const availableReactions = useMemo(() => {
    const allElementsSelected = currentFocusElement.map((ele) => ele.name);

    return allElementsSelected.length > 0 ? reactions
      .filter((reaction) => allElementsSelected.every((ele) => reaction.search.includes(ele))) : [];
  }, [currentFocusElement]);

  const handleClick = (element) => {
    dispatch(setElement(element.name));
    setCurrentFocusElement([element]);
  };

  return (
    <Wrapper>
      <section className="reactions_container">
        <h1>Choose an element</h1>
        <div className="element_section">
          {elements.map((element) => (
            <element.Component
              key={element.name}
              className={`elements ${currentFocusElement.some((ele) => ele.name === element.name) ? '' : ' elements_inactive'}`}
              onClick={() => handleClick(element)}
              size="45"
              color={element.color}
            />
          ))}
        </div>
        <div className="reactions_section">
          {availableReactions && availableReactions.map((element) => (
            <Reaction
              key={element.name}
              name={element.name}
              description={element.description}
              primaryComponent={currentFocusElement[0]}
              types={element.types}
            />
          ))}
        </div>
      </section>
    </Wrapper>
  );
}