Ensure useState doesn't re-init with function calls (#4552)

* Ensure useState doesn't re-init with function calls

* extra

* Additional
This commit is contained in:
Jaco Greeff 2021-02-01 14:17:14 +01:00 committed by GitHub
parent 1670ec2039
commit 1b43ffa046
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
35 changed files with 50 additions and 57 deletions

View File

@ -121,10 +121,10 @@ function loadAffinities (groups: Group[]): Record<string, string> {
function Endpoints ({ className = '', offset, onClose }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const linkOptions = createWsEndpoints(t);
const [groups, setGroups] = useState(combineEndpoints(linkOptions));
const [{ apiUrl, groupIndex, hasUrlChanged, isUrlValid }, setApiUrl] = useState<UrlState>(extractUrlState(settings.get().apiUrl, groups));
const [storedCustomEndpoints, setStoredCustomEndpoints] = useState<string[]>(getCustomEndpoints());
const [affinities, setAffinities] = useState(loadAffinities(groups));
const [groups, setGroups] = useState(() => combineEndpoints(linkOptions));
const [{ apiUrl, groupIndex, hasUrlChanged, isUrlValid }, setApiUrl] = useState<UrlState>(() => extractUrlState(settings.get().apiUrl, groups));
const [storedCustomEndpoints, setStoredCustomEndpoints] = useState<string[]>(() => getCustomEndpoints());
const [affinities, setAffinities] = useState(() => loadAffinities(groups));
const isKnownUrl = useMemo(() => {
let result = false;

View File

@ -28,7 +28,7 @@ function createTheme ({ uiTheme }: { uiTheme: string }): ThemeDef {
}
function Root ({ store }: Props): React.ReactElement<Props> {
const [theme, setTheme] = useState(createTheme(settings));
const [theme, setTheme] = useState(() => createTheme(settings));
useEffect((): void => {
settings.on('change', (settings) => setTheme(createTheme(settings)));

View File

@ -26,7 +26,7 @@ const JUDGEMENT_ENUM = [
function RegistrarJudgement ({ address, registrars, toggleJudgement }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const { api } = useApi();
const [addresses] = useState(registrars.map(({ address }) => address));
const [addresses] = useState(() => registrars.map(({ address }) => address));
const [judgementAccountId, setJudgementAccountId] = useState<string | null>(null);
const [judgementEnum, setJudgementEnum] = useState(2); // Reasonable
const [registrarIndex, setRegistrarIndex] = useState(-1);

View File

@ -185,7 +185,7 @@ function createAccount (suri: string, pairType: KeypairType, { genesisHash, name
function Create ({ className = '', onClose, onStatusChange, seed: propsSeed, type: propsType }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const { api, isDevelopment, isEthereum } = useApi();
const [{ address, derivePath, deriveValidation, isSeedValid, pairType, seed, seedType }, setAddress] = useState<AddressState>(generateSeed(propsSeed, '', propsSeed ? 'raw' : 'bip', isEthereum ? 'ethereum' : propsType));
const [{ address, derivePath, deriveValidation, isSeedValid, pairType, seed, seedType }, setAddress] = useState<AddressState>(() => generateSeed(propsSeed, '', propsSeed ? 'raw' : 'bip', isEthereum ? 'ethereum' : propsType));
const [isMnemonicSaved, setIsMnemonicSaved] = useState<boolean>(false);
const [step, setStep] = useState(1);
const [isBusy, setIsBusy] = useState(false);

View File

@ -83,7 +83,7 @@ function Derive ({ className = '', from, onClose }: Props): React.ReactElement {
const { t } = useTranslation();
const { api, isDevelopment } = useApi();
const { queueAction } = useContext(StatusContext);
const [source] = useState(keyring.getPair(from));
const [source] = useState(() => keyring.getPair(from));
const [isBusy, setIsBusy] = useState(false);
const [{ address, deriveError }, setDerive] = useState<DeriveAddress>({ address: null, deriveError: null });
const [isConfirmationOpen, toggleConfirmation] = useToggle();

View File

@ -80,17 +80,13 @@ function IdentityMain ({ address, className = '', onClose }: Props): React.React
const identityOpt = useCall<Option<Registration>>(api.query.identity.identityOf, [address]);
const [{ info, okAll, okDisplay, okEmail, okLegal, okRiot, okTwitter, okWeb }, setInfo] = useState<ValueState>({ info: {}, okAll: false });
const [hasEmail, setHasEmail] = useState(false);
// const [hasImg, setHasImg] = useState(false);
const [hasLegal, setHasLegal] = useState(false);
// const [hasPgp, setHasPgp] = useState(false);
const [hasRiot, setHasRiot] = useState(false);
const [hasTwitter, setHasTwitter] = useState(false);
const [hasWeb, setHasWeb] = useState(false);
const [valDisplay, setValDisplay] = useState((getAddressMeta(address).name || '').replace(/\(.*\)/, '').trim());
const [valDisplay, setValDisplay] = useState(() => (getAddressMeta(address).name || '').replace(/\(.*\)/, '').trim());
const [valEmail, setValEmail] = useState('');
// const [{ errImg, valImg }, setValImg] = useState<{ errImg: boolean; valImg: string }>({ errImg: true, valImg: '' });
const [valLegal, setValLegal] = useState('');
// const [{ errPgp, valPgp }, setValPgp] = useState<{ errPgp: boolean; valPgp: string }>({ errPgp: true, valPgp: '' });
const [valRiot, setValRiot] = useState('');
const [valTwitter, setValTwitter] = useState('');
const [valWeb, setValWeb] = useState('');
@ -135,8 +131,6 @@ function IdentityMain ({ address, className = '', onClose }: Props): React.React
riot: { [okRiot && hasRiot ? 'raw' : 'none']: okRiot && hasRiot ? valRiot : null },
twitter: { [okTwitter && hasTwitter ? 'raw' : 'none']: okTwitter && hasTwitter ? valTwitter : null },
web: { [okWeb && hasWeb ? 'raw' : 'none']: okWeb && hasWeb ? valWeb : null }
// image: { [hasImg ? 'sha256' : 'none']: hasImg ? valImg : null },
// pgpFingerprint: hasPgp ? valPgp : null
},
okAll: okDisplay && okEmail && okLegal && okRiot && okTwitter && okWeb,
okDisplay,
@ -146,7 +140,6 @@ function IdentityMain ({ address, className = '', onClose }: Props): React.React
okTwitter,
okWeb
});
// errImg, errPgp, hasImg, hasPgp, valImg, valPgp,
}, [hasEmail, hasLegal, hasRiot, hasTwitter, hasWeb, valDisplay, valEmail, valLegal, valRiot, valTwitter, valWeb]);
return (

View File

@ -26,8 +26,8 @@ const NOW_INC = 30 * 1000;
function CalendarApp ({ basePath, className }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const scheduled = useScheduled();
const [now, setNow] = useState(new Date());
const [dateState, setDateState] = useState(getDateState(now, now));
const [now, setNow] = useState(() => new Date());
const [dateState, setDateState] = useState(() => getDateState(now, now));
const [allEventsView, setAllEventsView] = useState(false);
const itemsRef = useRef([{

View File

@ -37,7 +37,7 @@ function Deploy ({ codeHash, constructorIndex = 0, onClose, setConstructorIndex
const [params, setParams] = useState<any[]>([]);
const [accountId, isAccountIdValid, setAccountId] = useFormField<string | null>(null);
const [endowment, isEndowmentValid, setEndowment] = useNonZeroBn(new BN(ENDOWMENT));
const [salt, setSalt] = useState(randomAsHex());
const [salt, setSalt] = useState(() => randomAsHex());
const [withSalt, setWithSalt] = useState(false);
useEffect((): void => {

View File

@ -29,8 +29,8 @@ function Contracts ({ className = '' }: Props): React.ReactElement<Props> {
const [isDeployOpen, toggleDeploy, setIsDeployOpen] = useToggle();
const [isHashOpen, toggleHash] = useToggle();
const [isUploadOpen, toggleUpload] = useToggle();
const [updated, setUpdated] = useState(Date.now());
const [allCodes, setAllCodes] = useState(store.getAllCode());
const [updated, setUpdated] = useState(() => Date.now());
const [allCodes, setAllCodes] = useState(() => store.getAllCode());
const _onShowDeploy = useCallback(
(codeHash: string, constructorIndex: number): void => {

View File

@ -47,7 +47,7 @@ const EMPTY: AbiState = {
};
export default function useAbi (initialValue: [string | null | undefined, Abi | null | undefined] = [null, null], codeHash: string | null = null, isRequired = false): UseAbi {
const [state, setAbi] = useState<AbiState>(fromInitial(initialValue, isRequired));
const [state, setAbi] = useState<AbiState>(() => fromInitial(initialValue, isRequired));
useEffect(
() => setAbi((state) =>

View File

@ -34,7 +34,7 @@ function NodeInfo (): React.ReactElement {
const { t } = useTranslation();
const { api } = useApi();
const [info, setInfo] = useState<Partial<Info>>({});
const [nextRefresh, setNextRefresh] = useState(Date.now());
const [nextRefresh, setNextRefresh] = useState(() => Date.now());
useEffect((): () => void => {
const _getStatus = (): void => {

View File

@ -28,7 +28,7 @@ function stateFromValue (value: string): State {
function Query ({ className = '', value: propsValue }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const [{ isValid, value }, setState] = useState(stateFromValue(propsValue || ''));
const [{ isValid, value }, setState] = useState(() => stateFromValue(propsValue || ''));
const _setHash = useCallback(
(value: string): void => setState(stateFromValue(value)),

View File

@ -37,7 +37,7 @@ export default function useProposals (): Proposals | undefined {
const { api } = useApi();
const mountedRef = useIsMountedRef();
const [state, setState] = useState<Proposals | undefined>();
const [trigger, setTrigger] = useState(Date.now());
const [trigger, setTrigger] = useState(() => Date.now());
const [events, sessionIndex, approvedIds] = useCallMulti<MultiQuery>([
api.query.system.events,
api.query.session.currentIndex,

View File

@ -49,8 +49,8 @@ function Propose ({ className, onClose }: Props): React.ReactElement<Props> {
const { api } = useApi();
const [accountId, setAccountId] = useState<string | null>(null);
const [name, setName] = useState('');
const [paraId, setParaId] = useState(new BN(Date.now() % 131072));
const [balance, setBalance] = useState(new BN(1000).mul(BN_TEN.pow(new BN(api.registry.chainDecimals))));
const [paraId, setParaId] = useState(() => new BN(Date.now() % 131072));
const [balance, setBalance] = useState(() => new BN(1000).mul(BN_TEN.pow(new BN(api.registry.chainDecimals[0]))));
const [validators, setValidators] = useState<string[]>(['']);
const [{ isWasmValid, wasm }, setWasm] = useState<CodeState>({ isWasmValid: false, wasm: null });
const [genesisState, setGenesisState] = useState<Uint8Array | null>(null);

View File

@ -38,7 +38,7 @@ interface SignerState {
function Sign ({ className = '' }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const [currentPair, setCurrentPair] = useState<KeyringPair | null>(keyring.getPairs()[0] || null);
const [currentPair, setCurrentPair] = useState<KeyringPair | null>(() => keyring.getPairs()[0] || null);
const [{ data, isHexData }, setData] = useState<DataState>({ data: '', isHexData: false });
const [{ isInjected }, setAccountState] = useState<AccountState>({ isExternal: false, isHardware: false, isInjected: false });
const [isLocked, setIsLocked] = useState(false);

View File

@ -26,7 +26,7 @@ function Member ({ className = '', isHead, value: { accountId, strikes } }: Prop
const { t } = useTranslation();
const { api } = useApi();
const canvasRef = useRef<HTMLCanvasElement | null>(null);
const [canInk] = useState(api.genesisHash.eq('0xb0a8d493285c2df73290dfb7e61f870f17b41801197a149ca93654499ea3dafe'));
const [canInk] = useState(() => api.genesisHash.eq('0xb0a8d493285c2df73290dfb7e61f870f17b41801197a149ca93654499ea3dafe'));
const [isInkShowing, toggleInk] = useToggle();
useEffect((): void => {

View File

@ -22,8 +22,8 @@ interface Props {
function SetRewardDestination ({ controllerId, defaultDestination, onClose, stashId }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const { api } = useApi();
const [destination, setDestination] = useState<DestinationType>(((defaultDestination?.isAccount ? 'Account' : defaultDestination?.toString()) || 'Staked') as 'Staked');
const [destAccount, setDestAccount] = useState<string | null>(defaultDestination?.isAccount ? defaultDestination.asAccount.toString() : null);
const [destination, setDestination] = useState<DestinationType>(() => ((defaultDestination?.isAccount ? 'Account' : defaultDestination?.toString()) || 'Staked') as 'Staked');
const [destAccount, setDestAccount] = useState<string | null>(() => defaultDestination?.isAccount ? defaultDestination.asAccount.toString() : null);
const options = useMemo(
() => createDestCurr(t),

View File

@ -26,7 +26,7 @@ function Unbond ({ className = '', controllerId, onClose, stakingLedger, stashId
const { t } = useTranslation();
const { api } = useApi();
const bondedBlocks = useUnbondDuration();
const [maxBalance] = useState<BN | null>(stakingLedger?.active.unwrap() || null);
const [maxBalance] = useState<BN | null>(() => stakingLedger?.active.unwrap() || null);
const [maxUnbond, setMaxUnbond] = useState<BN | null>(null);
const [withMax, setWithMax] = useState(false);

View File

@ -153,8 +153,8 @@ function getOptions (api: ApiPromise, eraLength: BN | undefined, historyDepth: B
function Payouts ({ className = '', isInElection, ownValidators }: Props): React.ReactElement<Props> {
const { t } = useTranslation();
const { api } = useApi();
const [hasOwnValidators] = useState(ownValidators.length !== 0);
const [myStashesIndex, setMyStashesIndex] = useState((api.tx.staking.payoutStakers && hasOwnValidators) ? 0 : 1);
const [hasOwnValidators] = useState(() => ownValidators.length !== 0);
const [myStashesIndex, setMyStashesIndex] = useState(() => (api.tx.staking.payoutStakers && hasOwnValidators) ? 0 : 1);
const [eraSelectionIndex, setEraSelectionIndex] = useState(0);
const eraLength = useCall<BN>(api.derive.session.eraLength);
const historyDepth = useCall<BN>(api.query.staking.historyDepth);

View File

@ -24,7 +24,7 @@ const HIGHLIGHTS = ['counter', 'highlight'];
let badgeId = 0;
function Badge ({ className = '', color = 'normal', hover, icon, info, isSmall, onClick }: Props): React.ReactElement<Props> | null {
const [trigger] = useState(`badge-hover-${Date.now()}-${badgeId++}`);
const [trigger] = useState(() => `badge-hover-${Date.now()}-${badgeId++}`);
const extraProps = hover
? { 'data-for': trigger, 'data-tip': true }
: {};

View File

@ -86,7 +86,7 @@ function DemocracyLocks ({ className = '', value }: Props): React.ReactElement<P
const { t } = useTranslation();
const { api } = useApi();
const bestNumber = useCall<BN>(api.derive.chain.bestNumber);
const [trigger] = useState(`${Date.now()}-democracy-locks-${++id}`);
const [trigger] = useState(() => `${Date.now()}-democracy-locks-${++id}`);
const [{ maxBalance, sorted }, setState] = useState<State>({ maxBalance: BN_ZERO, sorted: [] });
useEffect((): void => {

View File

@ -38,7 +38,7 @@ interface Props {
* ```
*/
function Editor ({ className = '', code, isValid, onEdit }: Props): React.ReactElement<Props> {
const [editorId] = useState(`flask-${Date.now()}`);
const [editorId] = useState(() => `flask-${Date.now()}`);
const editorRef = useRef<CodeFlask | null>(null);
useEffect((): void => {

View File

@ -93,7 +93,7 @@ const isSelectAll = (key: string, isPreKeyDown: boolean): boolean =>
let counter = 0;
function Input ({ autoFocus = false, children, className, defaultValue, help, icon, inputClassName, isAction = false, isDisabled = false, isDisabledError = false, isEditable = false, isError = false, isFull = false, isHidden = false, isInPlaceEditor = false, isReadOnly = false, isWarning = false, label, labelExtra, max, maxLength, min, name, onBlur, onChange, onEnter, onEscape, onKeyDown, onKeyUp, onPaste, placeholder, tabIndex, type = 'text', value, withEllipsis, withLabel }: Props): React.ReactElement<Props> {
const [stateName] = useState(`in_${counter++}_at_${Date.now()}`);
const [stateName] = useState(() => `in_${counter++}_at_${Date.now()}`);
const _onBlur = useCallback(
() => onBlur && onBlur(),

View File

@ -41,9 +41,9 @@ function getValue (api: ApiPromise, { method, section }: ConstValueBase): ConstV
function InputConsts ({ className = '', defaultValue, help, label, onChange, withLabel }: Props): React.ReactElement<Props> {
const { api } = useApi();
const [optionsMethod, setOptionsMethod] = useState<DropdownOptions>(keyOptions(api, defaultValue.section));
const [optionsSection] = useState<DropdownOptions>(sectionOptions(api));
const [value, setValue] = useState<ConstValue>(getValue(api, defaultValue));
const [optionsMethod, setOptionsMethod] = useState<DropdownOptions>(() => keyOptions(api, defaultValue.section));
const [optionsSection] = useState<DropdownOptions>(() => sectionOptions(api));
const [value, setValue] = useState<ConstValue>(() => getValue(api, defaultValue));
const _onKeyChange = useCallback(
(newValue: ConstValueBase): void => {

View File

@ -28,8 +28,8 @@ interface Props {
function InputExtrinsic ({ className = '', defaultValue, help, label, onChange, withLabel }: Props): React.ReactElement<Props> {
const { api } = useApi();
const [optionsMethod, setOptionsMethod] = useState<DropdownOptions>(methodOptions(api, defaultValue.section));
const [optionsSection] = useState<DropdownOptions>(sectionOptions(api));
const [optionsMethod, setOptionsMethod] = useState<DropdownOptions>(() => methodOptions(api, defaultValue.section));
const [optionsSection] = useState<DropdownOptions>(() => sectionOptions(api));
const [value, setValue] = useState<SubmittableExtrinsicFunction<'promise'>>((): SubmittableExtrinsicFunction<'promise'> => defaultValue);
const _onKeyChange = useCallback(

View File

@ -30,8 +30,8 @@ interface Props {
function InputRpc ({ className = '', defaultValue, help, label, onChange, withLabel }: Props): React.ReactElement<Props> {
const { api } = useApi();
const rpcs = useRpcs();
const [optionsMethod, setOptionsMethod] = useState<DropdownOptions>(methodOptions(api, rpcs, defaultValue.section));
const [optionsSection] = useState<DropdownOptions>(sectionOptions(api));
const [optionsMethod, setOptionsMethod] = useState<DropdownOptions>(() => methodOptions(api, rpcs, defaultValue.section));
const [optionsSection] = useState<DropdownOptions>(() => sectionOptions(api));
const [value, setValue] = useState<DefinitionRpcExt>((): DefinitionRpcExt => defaultValue);
useEffect((): void => {

View File

@ -28,9 +28,9 @@ interface Props {
function InputStorage ({ className = '', defaultValue, help, label, onChange, withLabel }: Props): React.ReactElement<Props> {
const { api } = useApi();
const [optionsMethod, setOptionsMethod] = useState<DropdownOptions>(keyOptions(api, defaultValue.creator.section));
const [optionsSection] = useState<DropdownOptions>(sectionOptions(api));
const [value, setValue] = useState<QueryableStorageEntry<'promise'>>(() => defaultValue);
const [optionsMethod, setOptionsMethod] = useState<DropdownOptions>(() => keyOptions(api, defaultValue.creator.section));
const [optionsSection] = useState<DropdownOptions>(() => sectionOptions(api));
const [value, setValue] = useState<QueryableStorageEntry<'promise'>>(defaultValue);
const _onKeyChange = useCallback(
(newValue: QueryableStorageEntry<'promise'>): void => {

View File

@ -18,7 +18,7 @@ interface Props {
let id = 0;
function LabelHelp ({ className = '', help, icon = 'question-circle' }: Props): React.ReactElement<Props> {
const [trigger] = useState(`label-help-${++id}`);
const [trigger] = useState(() => `label-help-${++id}`);
return (
<div className={`ui--LabelHelp ${className}`}>

View File

@ -20,7 +20,7 @@ interface Props {
let tagId = 0;
function Tag ({ className = '', color = 'grey', hover, isTag = true, label, size = 'small' }: Props): React.ReactElement<Props> {
const [trigger] = useState(`tag-hover-${Date.now()}-${tagId++}`);
const [trigger] = useState(() => `tag-hover-${Date.now()}-${tagId++}`);
const tooltipProps = hover
? { 'data-for': trigger, 'data-tip': true }
: {};

View File

@ -112,7 +112,7 @@ export function extractIpfsDetails (): State {
}
export function useIpfs (): State {
const [state] = useState(extractIpfsDetails());
const [state] = useState(() => extractIpfsDetails());
return state;
}

View File

@ -37,8 +37,8 @@ function getSetters <T extends Flags> (flags: T, setFlags: React.Dispatch<React.
}
export function useSavedFlags <T extends Flags> (storageKey: string, initial: T): State<T> {
const [flags, setFlags] = useState(getInitial(storageKey, initial));
const [setters] = useState(getSetters(initial, setFlags));
const [flags, setFlags] = useState(() => getInitial(storageKey, initial));
const [setters] = useState(() => getSetters(initial, setFlags));
useEffect(
(): void => {

View File

@ -11,7 +11,7 @@ import { keyring } from '@polkadot/ui-keyring';
import Bare from './Bare';
function Account ({ className = '', defaultValue: { value }, isDisabled, isError, isInOption, label, onChange, withLabel }: Props): React.ReactElement<Props> {
const [defaultValue] = useState((value as string)?.toString());
const [defaultValue] = useState(() => (value as string)?.toString());
const _onChange = useCallback(
(value?: string | null): void => {

View File

@ -12,7 +12,7 @@ import Bare from './Bare';
function Balance ({ className = '', defaultValue: { value }, isDisabled, isError, label, onChange, onEnter, onEscape, withLabel }: Props): React.ReactElement<Props> {
const [isValid, setIsValid] = useState(false);
const [defaultValue] = useState(new BN((value as BN || '0').toString()).toString(10));
const [defaultValue] = useState(() => new BN((value as BN || '0').toString()).toString(10));
const _onChange = useCallback(
(value?: BN): void => {

View File

@ -21,7 +21,7 @@ interface Props {
function SignFields ({ address, onChange, signedTx }: Props): React.ReactElement<Props> {
const { api } = useApi();
const [blocks, setBlocks] = useState(new BN(64));
const [blocks, setBlocks] = useState(() => new BN(64));
const [nonce, setNonce] = useState(BN_ZERO);
const { t } = useTranslation();

View File

@ -162,7 +162,7 @@ function TxSigned ({ className, currentItem, requestAddress }: Props): React.Rea
const { api } = useApi();
const { getLedger } = useLedger();
const { queueSetTxStatus } = useContext(StatusContext);
const [flags, setFlags] = useState(extractExternal(requestAddress));
const [flags, setFlags] = useState(() => extractExternal(requestAddress));
const [error, setError] = useState<Error | null>(null);
const [{ isQrHashed, qrAddress, qrPayload, qrResolve }, setQrState] = useState<QrState>({ isQrHashed: false, qrAddress: '', qrPayload: new Uint8Array() });
const [isBusy, setBusy] = useState(false);