From 4d17d5236d62c84009351b043993e53ee9fbd670 Mon Sep 17 00:00:00 2001 From: Jaco Greeff Date: Tue, 7 Apr 2020 16:07:11 +0200 Subject: [PATCH] Additional useCallback (close to 100%) (#2527) --- .../src/Accounts/modals/Create.tsx | 13 +- .../page-accounts/src/Contacts/Address.tsx | 184 ++++++++++-------- packages/page-generic-asset/src/AssetCard.tsx | 25 ++- packages/page-js/src/ActionButtons.tsx | 38 ++-- packages/page-js/src/Playground.tsx | 177 +++++++++-------- .../src/Overview/Parachain.tsx | 11 +- packages/page-settings/src/Developer.tsx | 165 +++++++++------- .../page-staking/src/Overview/CurrentList.tsx | 43 ++-- packages/page-storage/src/Query.tsx | 52 +++-- .../page-storage/src/Selection/Consts.tsx | 7 +- .../page-storage/src/Selection/Modules.tsx | 43 ++-- packages/page-storage/src/Selection/Raw.tsx | 29 +-- .../page-tech-comm/src/Proposals/Voting.tsx | 8 +- packages/page-toolbox/src/Sign.tsx | 85 ++++---- packages/page-toolbox/src/Verify.tsx | 35 ++-- .../page-treasury/src/Overview/Proposals.tsx | 11 +- .../page-treasury/src/Overview/Voting.tsx | 35 ++-- .../src/InputConsts/index.tsx | 44 +++-- .../src/InputExtrinsic/index.tsx | 40 ++-- .../src/InputStorage/index.tsx | 40 ++-- 20 files changed, 614 insertions(+), 471 deletions(-) diff --git a/packages/page-accounts/src/Accounts/modals/Create.tsx b/packages/page-accounts/src/Accounts/modals/Create.tsx index 8b662f14f2..3861a4a760 100644 --- a/packages/page-accounts/src/Accounts/modals/Create.tsx +++ b/packages/page-accounts/src/Accounts/modals/Create.tsx @@ -199,11 +199,14 @@ function Create ({ className, onClose, onStatusChange, seed: propsSeed, type: pr [derivePath, seed, seedType] ); - const _selectSeedType = (newSeedType: SeedType): void => { - if (newSeedType !== seedType) { - setAddress(generateSeed(null, derivePath, newSeedType, pairType)); - } - }; + const _selectSeedType = useCallback( + (newSeedType: SeedType): void => { + if (newSeedType !== seedType) { + setAddress(generateSeed(null, derivePath, newSeedType, pairType)); + } + }, + [derivePath, pairType, seedType] + ); const _onChangeName = useCallback( (name: string) => setName({ isNameValid: !!name.trim(), name }), diff --git a/packages/page-accounts/src/Contacts/Address.tsx b/packages/page-accounts/src/Contacts/Address.tsx index 9580778f8d..01464643b2 100644 --- a/packages/page-accounts/src/Contacts/Address.tsx +++ b/packages/page-accounts/src/Contacts/Address.tsx @@ -6,10 +6,10 @@ import { DeriveAccountInfo, DeriveBalancesAll } from '@polkadot/api-derive/types import { KeyringAddress } from '@polkadot/ui-keyring/types'; import { ActionStatus } from '@polkadot/react-components/Status/types'; -import React, { useEffect, useState } from 'react'; +import React, { useCallback, useEffect, useState } from 'react'; import styled from 'styled-components'; import { AddressSmall, AddressInfo, Button, ChainLock, Icon, InputTags, Input, LinkExternal, Forget, Menu, Popup, Tag } from '@polkadot/react-components'; -import { useApi, useCall } from '@polkadot/react-hooks'; +import { useApi, useCall, useToggle } from '@polkadot/react-hooks'; import keyring from '@polkadot/ui-keyring'; import { formatNumber } from '@polkadot/util'; @@ -37,14 +37,17 @@ function Address ({ address, className, filter, isFavorite, toggleFavorite }: Pr const [accName, setAccName] = useState(''); const [current, setCurrent] = useState(null); const [genesisHash, setGenesisHash] = useState(null); - const [isEditingName, setIsEditingName] = useState(false); - const [isEditingTags, setIsEditingTags] = useState(false); - const [isForgetOpen, setIsForgetOpen] = useState(false); - const [isSettingPopupOpen, setIsSettingPopupOpen] = useState(false); - const [isTransferOpen, setIsTransferOpen] = useState(false); + const [isEditingName, toggleEditName] = useToggle(); + const [isEditingTags, toggleEditTags] = useToggle(); + const [isForgetOpen, toggleForget] = useToggle(); + const [isSettingPopupOpen, toggleTransfer] = useToggle(); + const [isTransferOpen, toggleSettingPopup] = useToggle(); const [isVisible, setIsVisible] = useState(true); - const _setTags = (tags: string[]): void => setTags(tags.sort()); + const _setTags = useCallback( + (tags: string[]): void => setTags(tags.sort()), + [] + ); useEffect((): void => { const current = keyring.getAddress(address); @@ -71,7 +74,7 @@ function Address ({ address, className, filter, isFavorite, toggleFavorite }: Pr _setTags(account?.meta?.tags || []); setAccName(account?.meta?.name || ''); - }, [address]); + }, [_setTags, address]); useEffect((): void => { if (filter.length === 0) { @@ -87,78 +90,87 @@ function Address ({ address, className, filter, isFavorite, toggleFavorite }: Pr } }, [accName, filter, tags]); + const _onForget = useCallback( + (): void => { + if (address) { + const status: Partial = { + account: address, + action: 'forget' + }; + + try { + keyring.forgetAddress(address); + status.status = 'success'; + status.message = t('address forgotten'); + } catch (error) { + status.status = 'error'; + status.message = error.message; + } + } + }, + [address, t] + ); + + const _onGenesisChange = useCallback( + (genesisHash: string | null): void => { + setGenesisHash(genesisHash); + + const account = keyring.getAddress(address); + + account && keyring.saveAddress(address, { ...account.meta, genesisHash }); + + setGenesisHash(genesisHash); + }, + [address] + ); + + const _onFavorite = useCallback( + (): void => toggleFavorite(address), + [address, toggleFavorite] + ); + + const _saveName = useCallback( + (): void => { + toggleEditName(); + + const meta = { name: accName, whenEdited: Date.now() }; + + if (address) { + try { + const currentKeyring = keyring.getPair(address); + + currentKeyring && keyring.saveAccountMeta(currentKeyring, meta); + } catch (error) { + keyring.saveAddress(address, meta); + } + } + }, + [accName, address, toggleEditName] + ); + + const _saveTags = useCallback( + (): void => { + toggleEditTags(); + + const meta = { tags, whenEdited: Date.now() }; + + if (address) { + try { + const currentKeyring = keyring.getPair(address); + + currentKeyring && keyring.saveAccountMeta(currentKeyring, meta); + } catch (error) { + keyring.saveAddress(address, meta); + } + } + }, + [address, tags, toggleEditTags] + ); + if (!isVisible) { return null; } - const _toggleEditName = (): void => setIsEditingName(!isEditingName); - const _toggleEditTags = (): void => setIsEditingTags(!isEditingTags); - const _toggleForget = (): void => setIsForgetOpen(!isForgetOpen); - const _toggleSettingPopup = (): void => setIsSettingPopupOpen(!isSettingPopupOpen); - const _toggleTransfer = (): void => setIsTransferOpen(!isTransferOpen); - - const _onForget = (): void => { - if (address) { - const status: Partial = { - account: address, - action: 'forget' - }; - - try { - keyring.forgetAddress(address); - status.status = 'success'; - status.message = t('address forgotten'); - } catch (error) { - status.status = 'error'; - status.message = error.message; - } - } - }; - - const _onGenesisChange = (genesisHash: string | null): void => { - setGenesisHash(genesisHash); - - const account = keyring.getAddress(address); - - account && keyring.saveAddress(address, { ...account.meta, genesisHash }); - - setGenesisHash(genesisHash); - }; - - const _onFavorite = (): void => toggleFavorite(address); - - const _saveName = (): void => { - _toggleEditName(); - - const meta = { name: accName, whenEdited: Date.now() }; - - if (address) { - try { - const currentKeyring = keyring.getPair(address); - - currentKeyring && keyring.saveAccountMeta(currentKeyring, meta); - } catch (error) { - keyring.saveAddress(address, meta); - } - } - }; - - const _saveTags = (): void => { - _toggleEditTags(); - - const meta = { tags, whenEdited: Date.now() }; - - if (address) { - try { - const currentKeyring = keyring.getPair(address); - - currentKeyring && keyring.saveAccountMeta(currentKeyring, meta); - } catch (error) { - keyring.saveAddress(address, meta); - } - } - }; - return ( @@ -170,7 +182,7 @@ function Address ({ address, className, filter, isFavorite, toggleFavorite }: Pr )} {isTransferOpen && ( )} @@ -227,7 +239,7 @@ function Address ({ address, className, filter, isFavorite, toggleFavorite }: Pr : (
{tags.length ? tags.map((tag): React.ReactNode => ( @@ -258,30 +270,30 @@ function Address ({ address, className, filter, isFavorite, toggleFavorite }: Pr icon='paper plane' key='deposit' label={t('deposit')} - onClick={_toggleTransfer} + onClick={toggleTransfer} size='small' tooltip={t('Send funds to this address')} /> } > {t('Forget this address')} diff --git a/packages/page-generic-asset/src/AssetCard.tsx b/packages/page-generic-asset/src/AssetCard.tsx index f2a0aed999..ceb590e979 100644 --- a/packages/page-generic-asset/src/AssetCard.tsx +++ b/packages/page-generic-asset/src/AssetCard.tsx @@ -2,23 +2,32 @@ // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. -import React from 'react'; +import React, { useCallback } from 'react'; import { Card, Button } from '@polkadot/react-components'; -import { I18nProps } from '@polkadot/react-components/types'; import AssetRow from './AssetRow'; -import translate from './translate'; +import { useTranslation } from './translate'; -interface Props extends I18nProps { +interface Props { assetId: string; + className?: string; name: string; onSaveName: (id: string, name: string) => void; onForget: (id: string) => void; } -function AssetCard ({ assetId, className, name, onForget, onSaveName, t }: Props): React.ReactElement { - const _onForget = (): void => onForget(assetId); - const _onSaveName = (name: string): void => onSaveName(assetId, name); +function AssetCard ({ assetId, className, name, onForget, onSaveName }: Props): React.ReactElement { + const { t } = useTranslation(); + + const _onForget = useCallback( + (): void => onForget(assetId), + [assetId, onForget] + ); + + const _onSaveName = useCallback( + (name: string): void => onSaveName(assetId, name), + [assetId, onSaveName] + ); return ( @@ -44,4 +53,4 @@ function AssetCard ({ assetId, className, name, onForget, onSaveName, t }: Props ); } -export default translate(AssetCard); +export default React.memo(AssetCard); diff --git a/packages/page-js/src/ActionButtons.tsx b/packages/page-js/src/ActionButtons.tsx index 4e8f1d6d4e..af15b763cd 100644 --- a/packages/page-js/src/ActionButtons.tsx +++ b/packages/page-js/src/ActionButtons.tsx @@ -4,7 +4,7 @@ import { BareProps } from '@polkadot/react-components/types'; -import React, { useState } from 'react'; +import React, { useCallback, useState } from 'react'; import { Button as SUIB, Popup } from 'semantic-ui-react'; import { Button, Input } from '@polkadot/react-components'; @@ -25,23 +25,31 @@ function ActionButtons ({ className, isCustomExample, isRunning, removeSnippet, const [isOpen, setIsOpen] = useState(false); const [snippetName, setSnippetName] = useState(''); - const _onChangeName = (snippetName: string): void => { - setSnippetName(snippetName); - }; + const _onChangeName = useCallback( + (snippetName: string) => setSnippetName(snippetName), + [] + ); - const _onPopupOpen = (): void => { - setIsOpen(true); - }; + const _onPopupOpen = useCallback( + () => setIsOpen(true), + [] + ); - const _onPopupClose = (): void => { - setSnippetName(''); - setIsOpen(false); - }; + const _onPopupClose = useCallback( + (): void => { + setSnippetName(''); + setIsOpen(false); + }, + [] + ); - const _saveSnippet = (): void => { - saveSnippet(snippetName); - _onPopupClose(); - }; + const _saveSnippet = useCallback( + (): void => { + saveSnippet(snippetName); + _onPopupClose(); + }, + [_onPopupClose, saveSnippet, snippetName] + ); return (
diff --git a/packages/page-js/src/Playground.tsx b/packages/page-js/src/Playground.tsx index feb269c3c5..1769fa43e1 100644 --- a/packages/page-js/src/Playground.tsx +++ b/packages/page-js/src/Playground.tsx @@ -8,7 +8,7 @@ import { ApiProps } from '@polkadot/react-api/types'; import { AppProps as Props } from '@polkadot/react-components/types'; import { Log, LogType, Snippet } from './types'; -import React, { useRef, useState, useEffect } from 'react'; +import React, { useCallback, useRef, useState, useEffect } from 'react'; import styled from 'styled-components'; import { Button, Dropdown, Editor } from '@polkadot/react-components'; import { useApi } from '@polkadot/react-hooks'; @@ -113,90 +113,111 @@ function Playground ({ className }: Props): React.ReactElement { setCode(selected.code); }, [selected]); - const _clearConsole = (): void => setLogs([]); + const _clearConsole = useCallback( + (): void => setLogs([]), + [] + ); - const _hookConsole = (type: LogType, args: any[]): void => { - logs.push({ args, type }); - setLogs(logs.slice(0)); - }; + const _hookConsole = useCallback( + (type: LogType, args: any[]): void => { + logs.push({ args, type }); + setLogs(logs.slice(0)); + }, + [logs] + ); - const _stopJs = (): void => { - if (injectedRef.current) { - injectedRef.current.api.disconnect(); - injectedRef.current = null; - } - - setIsRunning(false); - }; - - const _runJs = async (): Promise => { - setIsRunning(true); - _clearConsole(); - - injectedRef.current = setupInjected(apiProps, setIsRunning, _hookConsole); - - await injectedRef.current.api.isReady; - - try { - // squash into a single line so exceptions (with line numbers) maps to the - // same line/origin as we have in the editor view - // TODO: Make the console.error here actually return the full stack - const exec = `(async ({${Object.keys(injectedRef.current).sort().join(',')}}) => { try { ${code} \n } catch (error) { console.error(error); setIsRunning(false); } })(injected);`; - - // eslint-disable-next-line no-new-func - new Function('injected', exec).bind({}, injectedRef.current)(); - } catch (error) { - injectedRef.current.console.error(error); - } - - setIsRunning(false); - }; - - const _selectExample = (value: string): void => { - _stopJs(); - - if (value.length) { - const option = options.find((option): boolean => option.value === value); - - if (option) { - localStorage.setItem(STORE_SELECTED, value); - - _clearConsole(); - setIsCustomExample(option.type === 'custom'); - setSelected(option); + const _stopJs = useCallback( + (): void => { + if (injectedRef.current) { + injectedRef.current.api.disconnect(); + injectedRef.current = null; } - } - }; - const _removeSnippet = (): void => { - const filtered = customExamples.filter((value): boolean => value.value !== selected.value); - const nextOptions = [...filtered, ...snippets]; + setIsRunning(false); + }, + [] + ); - setCustomExamples(filtered); - setIsCustomExample(nextOptions[0].type === 'custom'); - setOptions(nextOptions); - _selectExample(nextOptions[0].value); - localStorage.setItem(STORE_EXAMPLES, JSON.stringify(filtered)); - }; + const _runJs = useCallback( + async (): Promise => { + setIsRunning(true); + _clearConsole(); - const _saveSnippet = (snippetName: string): void => { - // The component doesn't take boolean custom props and no - // camelCase keys, that's why 'custom' is passed as a string here - const snapshot: Snippet = { - code, - label: CUSTOM_LABEL, - text: snippetName, - type: 'custom', - value: `custom-${Date.now()}` - }; - const options = [snapshot, ...customExamples, ...snippets]; + injectedRef.current = setupInjected(apiProps, setIsRunning, _hookConsole); - localStorage.setItem(STORE_EXAMPLES, JSON.stringify([snapshot, ...customExamples])); - setCustomExamples([snapshot, ...customExamples]); - setIsCustomExample(true); - setOptions(options); - setSelected(snapshot); - }; + await injectedRef.current.api.isReady; + + try { + // squash into a single line so exceptions (with line numbers) maps to the + // same line/origin as we have in the editor view + // TODO: Make the console.error here actually return the full stack + const exec = `(async ({${Object.keys(injectedRef.current).sort().join(',')}}) => { try { ${code} \n } catch (error) { console.error(error); setIsRunning(false); } })(injected);`; + + // eslint-disable-next-line no-new-func + new Function('injected', exec).bind({}, injectedRef.current)(); + } catch (error) { + injectedRef.current.console.error(error); + } + + setIsRunning(false); + }, + [_clearConsole, _hookConsole, apiProps, code] + ); + + const _selectExample = useCallback( + (value: string): void => { + _stopJs(); + + if (value.length) { + const option = options.find((option): boolean => option.value === value); + + if (option) { + localStorage.setItem(STORE_SELECTED, value); + + _clearConsole(); + setIsCustomExample(option.type === 'custom'); + setSelected(option); + } + } + }, + [_clearConsole, _stopJs, options] + ); + + const _removeSnippet = useCallback( + (): void => { + const filtered = customExamples.filter((value): boolean => value.value !== selected.value); + const nextOptions = [...filtered, ...snippets]; + + setCustomExamples(filtered); + setIsCustomExample(nextOptions[0].type === 'custom'); + setOptions(nextOptions); + _selectExample(nextOptions[0].value); + localStorage.setItem(STORE_EXAMPLES, JSON.stringify(filtered)); + }, + [_selectExample, customExamples, selected.value] + ); + + const _saveSnippet = useCallback( + (snippetName: string): void => { + // The component doesn't take boolean custom props and no + // camelCase keys, that's why 'custom' is passed as a string here + const snapshot: Snippet = { + code, + label: CUSTOM_LABEL, + text: snippetName, + type: 'custom', + value: `custom-${Date.now()}` + }; + const options = [snapshot, ...customExamples, ...snippets]; + + localStorage.setItem(STORE_EXAMPLES, JSON.stringify([snapshot, ...customExamples])); + setCustomExamples([snapshot, ...customExamples]); + setIsCustomExample(true); + setOptions(options); + setSelected(snapshot); + }, + [code, customExamples] + ); const snippetName = selected.type === 'custom' ? selected.text : undefined; diff --git a/packages/page-parachains/src/Overview/Parachain.tsx b/packages/page-parachains/src/Overview/Parachain.tsx index 609489150e..1bddb92025 100644 --- a/packages/page-parachains/src/Overview/Parachain.tsx +++ b/packages/page-parachains/src/Overview/Parachain.tsx @@ -4,7 +4,7 @@ import { DeriveParachain } from '@polkadot/api-derive/types'; -import React from 'react'; +import React, { useCallback } from 'react'; import { useHistory } from 'react-router-dom'; import styled from 'styled-components'; import { Badge, Icon } from '@polkadot/react-components'; @@ -21,9 +21,12 @@ function Parachain ({ className, parachain: { didUpdate, id, info, pendingSwapId const { t } = useTranslation(); const history = useHistory(); - const _onClick = (): void => { - history.push(`/parachains/${id.toString()}`); - }; + const _onClick = useCallback( + (): void => { + history.push(`/parachains/${id.toString()}`); + }, + [history, id] + ); return ( ; + typesPlaceholder: string | null; +} + function Developer ({ className, onStatusChange }: Props): React.ReactElement { const { t } = useTranslation(); const [code, setCode] = useState(EMPTY_CODE); @@ -35,87 +43,102 @@ function Developer ({ className, onStatusChange }: Props): React.ReactElement; typesPlaceholder: string | null }): void => { - setCode(code); - setIsJsonValid(isJsonValid); - setIsTypesValid(isTypesValid); - setTypes(types); - setTypesPlaceholder(typesPlaceholder); - }; + const _setState = useCallback( + ({ code, isJsonValid, isTypesValid, types, typesPlaceholder }: AllState): void => { + setCode(code); + setIsJsonValid(isJsonValid); + setIsTypesValid(isTypesValid); + setTypes(types); + setTypesPlaceholder(typesPlaceholder); + }, + [] + ); - const _clearTypes = (): void => { - store.remove('types'); - - _setState({ - code: EMPTY_CODE, - isJsonValid: true, - isTypesValid: true, - types: EMPTY_TYPES, - typesPlaceholder: null - }); - }; - - const _onChangeTypes = (data: Uint8Array): void => { - const code = u8aToString(data); - - try { - const types = JSON.parse(code); - const typesPlaceholder = Object.keys(types).join(', '); - - console.log('Detected types:', typesPlaceholder); + const _clearTypes = useCallback( + (): void => { + store.remove('types'); _setState({ - code, + code: EMPTY_CODE, isJsonValid: true, isTypesValid: true, - types: Object.keys(types).length === 0 ? {} : types, - typesPlaceholder + types: EMPTY_TYPES, + typesPlaceholder: null }); - } catch (error) { - console.error('Error registering types:', error); + }, + [_setState] + ); - _setState({ - code, - isJsonValid: false, - isTypesValid: false, - types: {}, - typesPlaceholder: error.message - }); - } - }; + const _onChangeTypes = useCallback( + (data: Uint8Array): void => { + const code = u8aToString(data); - const _onEditTypes = (code: string): void => { - try { - if (!isJsonObject(code)) { - throw Error(t('This is not a valid JSON object.')); + try { + const types = JSON.parse(code); + const typesPlaceholder = Object.keys(types).join(', '); + + console.log('Detected types:', typesPlaceholder); + + _setState({ + code, + isJsonValid: true, + isTypesValid: true, + types: Object.keys(types).length === 0 ? {} : types, + typesPlaceholder + }); + } catch (error) { + console.error('Error registering types:', error); + + _setState({ + code, + isJsonValid: false, + isTypesValid: false, + types: {}, + typesPlaceholder: error.message + }); } + }, + [_setState] + ); - _onChangeTypes(stringToU8a(code)); - } catch (e) { - setCode(code); - setIsJsonValid(false); - setTypesPlaceholder(e.message); - } - }; + const _onEditTypes = useCallback( + (code: string): void => { + try { + if (!isJsonObject(code)) { + throw Error(t('This is not a valid JSON object.')); + } - const _saveDeveloper = (): void => { - try { - registry.register(types); - store.set('types', types); - setIsTypesValid(true); - onStatusChange({ - action: t('Your custom types have been added'), - status: 'success' - }); - } catch (error) { - console.error(error); - setIsTypesValid(false); - onStatusChange({ - action: t(`Error saving your custom types. ${error.message}`), - status: 'error' - }); - } - }; + _onChangeTypes(stringToU8a(code)); + } catch (e) { + setCode(code); + setIsJsonValid(false); + setTypesPlaceholder(e.message); + } + }, + [_onChangeTypes, t] + ); + + const _saveDeveloper = useCallback( + (): void => { + try { + registry.register(types); + store.set('types', types); + setIsTypesValid(true); + onStatusChange({ + action: t('Your custom types have been added'), + status: 'success' + }); + } catch (error) { + console.error(error); + setIsTypesValid(false); + onStatusChange({ + action: t(`Error saving your custom types. ${error.message}`), + status: 'error' + }); + } + }, + [onStatusChange, t, types] + ); const typesHasNoEntries = Object.keys(types).length === 0; diff --git a/packages/page-staking/src/Overview/CurrentList.tsx b/packages/page-staking/src/Overview/CurrentList.tsx index 02168d323d..01ff2c0955 100644 --- a/packages/page-staking/src/Overview/CurrentList.tsx +++ b/packages/page-staking/src/Overview/CurrentList.tsx @@ -6,7 +6,7 @@ import { DeriveHeartbeats, DeriveStakingOverview } from '@polkadot/api-derive/ty import { AccountId } from '@polkadot/types/interfaces'; import { AddressDetails } from './types'; -import React, { useEffect, useReducer, useState } from 'react'; +import React, { useCallback, useEffect, useReducer, useState } from 'react'; import { Input, Table } from '@polkadot/react-components'; import { useFavorites } from '@polkadot/react-hooks'; @@ -114,25 +114,28 @@ function CurrentList ({ authorsMap, hasQueries, isIntentions, lastAuthors, next, } }, [favorites, next, stakingOverview]); - const _renderRows = (addresses?: AccountExtend[], isMain?: boolean): React.ReactNode[] => - (addresses || []).map(([address, isElected, isFavorite]): React.ReactNode => ( -
- )); + const _renderRows = useCallback( + (addresses?: AccountExtend[], isMain?: boolean): React.ReactNode[] => + (addresses || []).map(([address, isElected, isFavorite]): React.ReactNode => ( +
+ )), + [addressDetails, authorsMap, hasQueries, isIntentions, lastAuthors, nameFilter, recentlyOnline, setNominators, toggleFavorite] + ); return isIntentions ? ( diff --git a/packages/page-storage/src/Query.tsx b/packages/page-storage/src/Query.tsx index b61d39fce0..d44cdee9ff 100644 --- a/packages/page-storage/src/Query.tsx +++ b/packages/page-storage/src/Query.tsx @@ -6,7 +6,7 @@ import { RenderFn, DefaultProps, ComponentRenderer } from '@polkadot/react-api/h import { ConstValue } from '@polkadot/react-components/InputConsts/types'; import { QueryTypes, StorageEntryPromise, StorageModuleQuery } from './types'; -import React, { useEffect, useState } from 'react'; +import React, { useCallback, useEffect, useState } from 'react'; import styled from 'styled-components'; import { unwrapStorageType } from '@polkadot/types/primitive/StorageKey'; import { Button, Labelled } from '@polkadot/react-components'; @@ -135,18 +135,6 @@ function Query ({ className, onRemove, value }: Props): React.ReactElement { setComponent(getCachedComponent(value)); - // setInputs( - // isU8a(value.key) - // ? [] - // // FIXME We need to render the actual key params - // // const { key, params } = value; - // // const inputs = key.params.map(({ name, type }, index) => ( - // // - // // {name}={valueToText(type, params[index].value)} - // // - // // )); - // : [] - // ); setIsSpreadable( (value.key as StorageEntryPromise).creator && (value.key as StorageEntryPromise).creator.meta && @@ -154,6 +142,28 @@ function Query ({ className, onRemove, value }: Props): React.ReactElement void => { + return (): void => { + cache[id].Component = cache[id].refresh(true, !!spread[id]); + spread[id] = !spread[id]; + + setComponent(cache[id]); + setSpread({ ...spread }); + }; + }, + [spread] + ); + + const _onRemove = useCallback( + (): void => { + delete cache[value.id]; + + onRemove(value.id); + }, + [onRemove, value] + ); + const { id, isConst, key } = value; const type = isConst ? (key as unknown as ConstValue).meta.type.toString() @@ -165,22 +175,6 @@ function Query ({ className, onRemove, value }: Props): React.ReactElement void => { - return (): void => { - cache[id].Component = cache[id].refresh(true, !!spread[id]); - spread[id] = !spread[id]; - - setComponent(cache[id]); - setSpread({ ...spread }); - }; - }; - - const _onRemove = (): void => { - delete cache[value.id]; - - onRemove(value.id); - }; - return (
diff --git a/packages/page-storage/src/Selection/Consts.tsx b/packages/page-storage/src/Selection/Consts.tsx index 1d0e64bde4..2afe21a2c9 100644 --- a/packages/page-storage/src/Selection/Consts.tsx +++ b/packages/page-storage/src/Selection/Consts.tsx @@ -6,7 +6,7 @@ import { ConstantCodec } from '@polkadot/metadata/Decorated/types'; import { ConstValue } from '@polkadot/react-components/InputConsts/types'; import { ComponentProps as Props } from '../types'; -import React, { useState } from 'react'; +import React, { useCallback, useState } from 'react'; import { Button, InputConsts } from '@polkadot/react-components'; import { useApi } from '@polkadot/react-hooks'; @@ -27,7 +27,10 @@ function Consts ({ onAdd }: Props): React.ReactElement { }); const [value, setValue] = useState(defaultValue); - const _onAdd = (): void => onAdd({ isConst: true, key: value }); + const _onAdd = useCallback( + () => onAdd({ isConst: true, key: value }), + [onAdd, value] + ); const { method, section } = value; const meta = (api.consts[section][method] as ConstantCodec).meta; diff --git a/packages/page-storage/src/Selection/Modules.tsx b/packages/page-storage/src/Selection/Modules.tsx index b1af28ccaa..db8b12ffe7 100644 --- a/packages/page-storage/src/Selection/Modules.tsx +++ b/packages/page-storage/src/Selection/Modules.tsx @@ -6,7 +6,7 @@ import { TypeDef } from '@polkadot/types/types'; import { RawParams } from '@polkadot/react-params/types'; import { ComponentProps as Props, StorageEntryPromise } from '../types'; -import React, { useState } from 'react'; +import React, { useCallback, useState } from 'react'; import ApiPromise from '@polkadot/api/promise'; import { Button, InputStorage } from '@polkadot/react-components'; import { useApi } from '@polkadot/react-hooks'; @@ -70,24 +70,33 @@ function Modules ({ onAdd }: Props): React.ReactElement { const [{ defaultValues, isIterable, key, params }, setKey] = useState({ defaultValues: undefined, isIterable: false, key: api.query.timestamp.now, params: [] }); const [{ isValid, values }, setValues] = useState<{ isValid: boolean; values: RawParams }>({ isValid: true, values: [] }); - const _onAdd = (): void => { - isValid && onAdd({ - isConst: false, - key, - params: values.filter(({ value }): boolean => !isIterable || !isNull(value)) - }); - }; + const _onAdd = useCallback( + (): void => { + isValid && onAdd({ + isConst: false, + key, + params: values.filter(({ value }): boolean => !isIterable || !isNull(value)) + }); + }, + [isIterable, isValid, key, onAdd, values] + ); - const _onChangeValues = (values: RawParams): void => - setValues({ - isValid: areParamsValid(key, values), - values - }); + const _onChangeValues = useCallback( + (values: RawParams): void => + setValues({ + isValid: areParamsValid(key, values), + values + }), + [key] + ); - const _onChangeKey = (key: StorageEntryPromise): void => { - setKey(expandKey(api, key)); - _onChangeValues([]); - }; + const _onChangeKey = useCallback( + (key: StorageEntryPromise): void => { + setKey(expandKey(api, key)); + _onChangeValues([]); + }, + [_onChangeValues, api] + ); const { creator: { meta, method, section } } = key; diff --git a/packages/page-storage/src/Selection/Raw.tsx b/packages/page-storage/src/Selection/Raw.tsx index c2c9bfffce..1a438c496f 100644 --- a/packages/page-storage/src/Selection/Raw.tsx +++ b/packages/page-storage/src/Selection/Raw.tsx @@ -4,7 +4,7 @@ import { ComponentProps as Props } from '../types'; -import React, { useState } from 'react'; +import React, { useCallback, useState } from 'react'; import { Button, Input } from '@polkadot/react-components'; import { useTranslation } from '../translate'; @@ -15,19 +15,24 @@ function Raw ({ onAdd }: Props): React.ReactElement { const { t } = useTranslation(); const [{ isValid, key }, setValue] = useState<{ isValid: boolean; key: Uint8Array }>({ isValid: false, key: new Uint8Array([]) }); - const _onAdd = (): void => { - isValid && onAdd({ isConst: false, key }); - }; + const _onAdd = useCallback( + (): void => { + isValid && onAdd({ isConst: false, key }); + }, + [isValid, key, onAdd] + ); - const _onChangeKey = (key: string): void => { - const u8a = u8aToU8a(key); - const isValid = u8a.length !== 0; + const _onChangeKey = useCallback( + (key: string): void => { + const u8a = u8aToU8a(key); - setValue({ - isValid, - key: Compact.addLengthPrefix(u8a) - }); - }; + setValue({ + isValid: u8a.length !== 0, + key: Compact.addLengthPrefix(u8a) + }); + }, + [] + ); return (
diff --git a/packages/page-tech-comm/src/Proposals/Voting.tsx b/packages/page-tech-comm/src/Proposals/Voting.tsx index 68a4660fa5..00163008ba 100644 --- a/packages/page-tech-comm/src/Proposals/Voting.tsx +++ b/packages/page-tech-comm/src/Proposals/Voting.tsx @@ -5,7 +5,7 @@ import { AccountId } from '@polkadot/types/interfaces'; import BN from 'bn.js'; -import React, { useState } from 'react'; +import React, { useCallback, useState } from 'react'; import { Button, Icon, Modal, VoteAccount, VoteActions, VoteToggle } from '@polkadot/react-components'; import { useAccounts, useToggle } from '@polkadot/react-hooks'; import { isBoolean } from '@polkadot/util'; @@ -25,11 +25,15 @@ function Voting ({ hash, prime, proposalId }: Props): React.ReactElement const [isVotingOpen, toggleVoting] = useToggle(); const [voteValue, setVoteValue] = useState(true); + const _onChangeVote = useCallback( + (vote?: boolean): void => setVoteValue(isBoolean(vote) ? vote : true), + [] + ); + if (!hasAccounts) { return null; } - const _onChangeVote = (vote?: boolean): void => setVoteValue(isBoolean(vote) ? vote : true); const isPrime = accountId === prime?.toString(); return ( diff --git a/packages/page-toolbox/src/Sign.tsx b/packages/page-toolbox/src/Sign.tsx index 4b6288c907..255e5972c7 100644 --- a/packages/page-toolbox/src/Sign.tsx +++ b/packages/page-toolbox/src/Sign.tsx @@ -5,10 +5,11 @@ import { Signer } from '@polkadot/api/types'; import { KeyringPair } from '@polkadot/keyring/types'; -import React, { useEffect, useState } from 'react'; +import React, { useCallback, useEffect, useState } from 'react'; import styled from 'styled-components'; import { web3FromSource } from '@polkadot/extension-dapp'; import { Button, Input, InputAddress, Output, Static } from '@polkadot/react-components'; +import { useToggle } from '@polkadot/react-hooks'; import keyring from '@polkadot/ui-keyring'; import { hexToU8a, isFunction, isHex, stringToHex, stringToU8a, u8aToHex } from '@polkadot/util'; @@ -37,7 +38,7 @@ function Sign ({ className }: Props): React.ReactElement { const [isLocked, setIsLocked] = useState(false); const [{ isUsable, signer }, setSigner] = useState<{ isUsable: boolean; signer: Signer | null }>({ isUsable: true, signer: null }); const [signature, setSignature] = useState(''); - const [isUnlockVisible, setIsUnlockVisible] = useState(false); + const [isUnlockVisible, toggleUnlock] = useToggle(); useEffect((): void => { const isExternal = currentPair?.meta.isExternal || false; @@ -71,42 +72,54 @@ function Sign ({ className }: Props): React.ReactElement { } }, [currentPair]); - const _toggleUnlock = (): void => setIsUnlockVisible(!isUnlockVisible); - const _onChangeAccount = (accountId: string | null): void => setCurrentPair(keyring.getPair(accountId || '')); - const _onChangeData = (data: string): void => setData({ data, isHexData: isHex(data) }); + const _onChangeAccount = useCallback( + (accountId: string | null) => setCurrentPair(keyring.getPair(accountId || '')), + [] + ); - const _onSign = (): void => { - if (isLocked || !isUsable || !currentPair) { - return; - } + const _onChangeData = useCallback( + (data: string) => setData({ data, isHexData: isHex(data) }), + [] + ); - if (signer?.signRaw) { - setSignature(''); + const _onSign = useCallback( + (): void => { + if (isLocked || !isUsable || !currentPair) { + return; + } - signer - .signRaw({ - address: currentPair.address, - data: isHexData - ? data - : stringToHex(data), - type: 'bytes' - }) - .then(({ signature }): void => setSignature(signature)); - } else { - setSignature(u8aToHex( - currentPair.sign( - isHexData - ? hexToU8a(data) - : stringToU8a(data) - ) - )); - } - }; + if (signer?.signRaw) { + setSignature(''); - const _onUnlock = (): void => { - setIsLocked(false); - _toggleUnlock(); - }; + signer + .signRaw({ + address: currentPair.address, + data: isHexData + ? data + : stringToHex(data), + type: 'bytes' + }) + .then(({ signature }): void => setSignature(signature)); + } else { + setSignature(u8aToHex( + currentPair.sign( + isHexData + ? hexToU8a(data) + : stringToU8a(data) + ) + )); + } + }, + [currentPair, data, isHexData, isLocked, isUsable, signer] + ); + + const _onUnlock = useCallback( + (): void => { + setIsLocked(false); + toggleUnlock(); + }, + [toggleUnlock] + ); return (
@@ -166,7 +179,7 @@ function Sign ({ className }: Props): React.ReactElement {
@@ -187,7 +200,7 @@ function Sign ({ className }: Props): React.ReactElement {
{isUnlockVisible && ( diff --git a/packages/page-toolbox/src/Verify.tsx b/packages/page-toolbox/src/Verify.tsx index bc3f9ece9b..26600e00d4 100644 --- a/packages/page-toolbox/src/Verify.tsx +++ b/packages/page-toolbox/src/Verify.tsx @@ -4,7 +4,7 @@ import { KeypairType } from '@polkadot/util-crypto/types'; -import React, { useEffect, useState } from 'react'; +import React, { useCallback, useEffect, useState } from 'react'; import { Dropdown, Icon, Input, InputAddress, Static } from '@polkadot/react-components'; import keyring from '@polkadot/ui-keyring'; import uiSettings from '@polkadot/ui-settings'; @@ -78,23 +78,30 @@ function Verify (): React.ReactElement<{}> { setValidity({ cryptoType, isValid }); }, [data, isValidPk, isValidSignature, publicKey, signature]); - const _onChangeAddress = (accountId: string | null): void => { - let publicKey: Uint8Array | null = null; + const _onChangeAddress = useCallback( + (accountId: string | null): void => { + let publicKey: Uint8Array | null = null; - try { - publicKey = keyring.decodeAddress(accountId || ''); - } catch (err) { - console.error(err); - } + try { + publicKey = keyring.decodeAddress(accountId || ''); + } catch (err) { + console.error(err); + } - setPublicKey({ isValidPk: !!publicKey && publicKey.length === 32, publicKey }); - }; + setPublicKey({ isValidPk: !!publicKey && publicKey.length === 32, publicKey }); + }, + [] + ); - const _onChangeData = (data: string): void => - setData({ data, isHexData: isHex(data) }); + const _onChangeData = useCallback( + (data: string) => setData({ data, isHexData: isHex(data) }), + [] + ); - const _onChangeSignature = (signature: string): void => - setSignature({ isValidSignature: isHex(signature) && signature.length === 130, signature }); + const _onChangeSignature = useCallback( + (signature: string) => setSignature({ isValidSignature: isHex(signature) && signature.length === 130, signature }), + [] + ); return (
diff --git a/packages/page-treasury/src/Overview/Proposals.tsx b/packages/page-treasury/src/Overview/Proposals.tsx index 0035a3a769..ed45e80a3e 100644 --- a/packages/page-treasury/src/Overview/Proposals.tsx +++ b/packages/page-treasury/src/Overview/Proposals.tsx @@ -5,7 +5,7 @@ import { DeriveTreasuryProposal } from '@polkadot/api-derive/types'; import { AccountId, Balance } from '@polkadot/types/interfaces'; -import React, { useEffect, useState } from 'react'; +import React, { useCallback, useEffect, useState } from 'react'; import { useHistory } from 'react-router-dom'; import { Table } from '@polkadot/react-components'; import { useApi, useAccounts, useCall } from '@polkadot/react-hooks'; @@ -35,9 +35,12 @@ function ProposalsBase ({ className, isApprovals, proposals }: Props): React.Rea ); }, [allAccounts, members]); - const _onRespond = (): void => { - history.push('/council/motions'); - }; + const _onRespond = useCallback( + (): void => { + history.push('/council/motions'); + }, + [history] + ); return ( setVoteValue(isBoolean(vote) ? vote : true), + [] + ); + + const _onChangeProposal = useCallback( + (optionId: number): void => { + const councilProp = councilProposals.find(({ votes }): boolean => !!(votes?.index.eq(optionId))); + + if (councilProp && councilProp.votes) { + setCouncilInfo({ councilHash: councilProp.hash, councilId: councilProp.votes.index }); + setCouncilOptId(councilOptId); + } else { + setCouncilInfo({ councilHash: null, councilId: null }); + } + }, + [councilOptId, councilProposals] + ); + if (!hasAccounts || !councilOpts.length) { return null; } - const _onChangeVote = (vote?: boolean): void => - setVoteValue(isBoolean(vote) ? vote : true); - - const _onChangeProposal = (optionId: number): void => { - const councilProp = councilProposals.find(({ votes }): boolean => !!(votes?.index.eq(optionId))); - - if (councilProp && councilProp.votes) { - setCouncilInfo({ councilHash: councilProp.hash, councilId: councilProp.votes.index }); - setCouncilOptId(councilOptId); - } else { - setCouncilInfo({ councilHash: null, councilId: null }); - } - }; - return ( <> {isOpen && ( diff --git a/packages/react-components/src/InputConsts/index.tsx b/packages/react-components/src/InputConsts/index.tsx index 623ec8f588..13766e4d74 100644 --- a/packages/react-components/src/InputConsts/index.tsx +++ b/packages/react-components/src/InputConsts/index.tsx @@ -6,7 +6,7 @@ import { ConstantCodec } from '@polkadot/metadata/Decorated/types'; import { DropdownOptions } from '../util/types'; import { ConstValue, ConstValueBase } from './types'; -import React, { useState } from 'react'; +import React, { useCallback, useState } from 'react'; import { ApiPromise } from '@polkadot/api'; import { useApi } from '@polkadot/react-hooks'; @@ -46,29 +46,35 @@ function InputConsts ({ className, defaultValue, help, label, onChange, style, w const [optionsSection] = useState(sectionOptions(api)); const [value, setValue] = useState(getValue(api, defaultValue)); - const _onKeyChange = (newValue: ConstValueBase): void => { - if (value.section === newValue.section && value.method === newValue.method) { - return; - } + const _onKeyChange = useCallback( + (newValue: ConstValueBase): void => { + if (value.section === newValue.section && value.method === newValue.method) { + return; + } - const { method, section } = newValue; - const meta = (api.consts[section][method] as ConstantCodec).meta; - const updated = { meta, method, section }; + const { method, section } = newValue; + const meta = (api.consts[section][method] as ConstantCodec).meta; + const updated = { meta, method, section }; - setValue(updated); - onChange && onChange(updated); - }; + setValue(updated); + onChange && onChange(updated); + }, + [api, onChange, value] + ); - const _onSectionChange = (section: string): void => { - if (section === value.section) { - return; - } + const _onSectionChange = useCallback( + (section: string): void => { + if (section === value.section) { + return; + } - const optionsMethod = keyOptions(api, section); + const optionsMethod = keyOptions(api, section); - setOptionsMethod(optionsMethod); - _onKeyChange({ method: optionsMethod[0].value, section }); - }; + setOptionsMethod(optionsMethod); + _onKeyChange({ method: optionsMethod[0].value, section }); + }, + [_onKeyChange, api, value] + ); return ( (sectionOptions(api)); const [value, setValue] = useState>((): SubmittableExtrinsicFunction<'promise'> => defaultValue); - const _onKeyChange = (newValue: SubmittableExtrinsicFunction<'promise'>): void => { - if (value.section === newValue.section && value.method === newValue.method) { - return; - } + const _onKeyChange = useCallback( + (newValue: SubmittableExtrinsicFunction<'promise'>): void => { + if (value.section === newValue.section && value.method === newValue.method) { + return; + } - // set this via callback, since the we are setting a function (alternatively... we have issues) - setValue((): SubmittableExtrinsicFunction<'promise'> => newValue); - onChange(newValue); - }; + // set this via callback, since the we are setting a function (alternatively... we have issues) + setValue((): SubmittableExtrinsicFunction<'promise'> => newValue); + onChange(newValue); + }, + [onChange, value] + ); - const _onSectionChange = (section: string): void => { - if (section === value.section) { - return; - } + const _onSectionChange = useCallback( + (section: string): void => { + if (section === value.section) { + return; + } - const optionsMethod = methodOptions(api, section); + const optionsMethod = methodOptions(api, section); - setOptionsMethod(optionsMethod); - _onKeyChange(api.tx[section][optionsMethod[0].value]); - }; + setOptionsMethod(optionsMethod); + _onKeyChange(api.tx[section][optionsMethod[0].value]); + }, + [_onKeyChange, api, value] + ); return ( (sectionOptions(api)); const [value, setValue] = useState((): StorageEntryPromise => defaultValue); - const _onKeyChange = (newValue: StorageEntryPromise): void => { - if (value.creator.section === newValue.creator.section && value.creator.method === newValue.creator.method) { - return; - } + const _onKeyChange = useCallback( + (newValue: StorageEntryPromise): void => { + if (value.creator.section === newValue.creator.section && value.creator.method === newValue.creator.method) { + return; + } - // set via callback - setValue((): StorageEntryPromise => newValue); - onChange && onChange(newValue); - }; + // set via callback + setValue((): StorageEntryPromise => newValue); + onChange && onChange(newValue); + }, + [onChange, value] + ); - const _onSectionChange = (section: string): void => { - if (section === value.creator.section) { - return; - } + const _onSectionChange = useCallback( + (section: string): void => { + if (section === value.creator.section) { + return; + } - const optionsMethod = keyOptions(api, section); + const optionsMethod = keyOptions(api, section); - setOptionsMethod(optionsMethod); - _onKeyChange(api.query[section][optionsMethod[0].value]); - }; + setOptionsMethod(optionsMethod); + _onKeyChange(api.query[section][optionsMethod[0].value]); + }, + [_onKeyChange, api, value] + ); return (