useMemo for complex computations in Country/State inputs (https://github.com/woocommerce/woocommerce-blocks/pull/3107)

This commit is contained in:
Albert Juhé Lluveras 2020-09-03 10:02:26 +02:00 committed by GitHub
parent 04cbd80b60
commit dfd57b0ee8
2 changed files with 20 additions and 11 deletions

View File

@ -1,6 +1,7 @@
/**
* External dependencies
*/
import { useMemo } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import PropTypes from 'prop-types';
import { decodeEntities } from '@wordpress/html-entities';
@ -27,10 +28,14 @@ const CountryInput = ( {
'woo-gutenberg-products-block'
),
} ) => {
const options = Object.keys( countries ).map( ( key ) => ( {
key,
name: decodeEntities( countries[ key ] ),
} ) );
const options = useMemo(
() =>
Object.keys( countries ).map( ( key ) => ( {
key,
name: decodeEntities( countries[ key ] ),
} ) ),
[ countries ]
);
return (
<div

View File

@ -4,7 +4,7 @@
import { __ } from '@wordpress/i18n';
import PropTypes from 'prop-types';
import { decodeEntities } from '@wordpress/html-entities';
import { useCallback } from '@wordpress/element';
import { useCallback, useMemo } from '@wordpress/element';
import classnames from 'classnames';
/**
@ -26,12 +26,16 @@ const StateInput = ( {
required = false,
} ) => {
const countryStates = states[ country ];
const options = countryStates
? Object.keys( countryStates ).map( ( key ) => ( {
key,
name: decodeEntities( countryStates[ key ] ),
} ) )
: [];
const options = useMemo(
() =>
countryStates
? Object.keys( countryStates ).map( ( key ) => ( {
key,
name: decodeEntities( countryStates[ key ] ),
} ) )
: [],
[ countryStates ]
);
/**
* Handles state selection onChange events. Finds a matching state by key or value.