Reinitialise useSelectShippingRate when rates change. (https://github.com/woocommerce/woocommerce-blocks/pull/2012)

* reinitilize the selected shipping rate

* useMemo instead of usePrevious
This commit is contained in:
Seghir Nadir 2020-03-26 13:40:56 +01:00 committed by GitHub
parent 4b80ef79ef
commit 06d4042567
1 changed files with 29 additions and 17 deletions

View File

@ -2,7 +2,7 @@
* External dependencies
*/
import { useDispatch } from '@wordpress/data';
import { useState } from '@wordpress/element';
import { useState, useEffect, useMemo } from '@wordpress/element';
import { CART_STORE_KEY as storeKey } from '@woocommerce/block-data';
import { useThrowError } from '@woocommerce/base-hooks';
@ -19,25 +19,37 @@ See also: https://github.com/woocommerce/woocommerce-gutenberg-products-block/tr
*/
export const useSelectShippingRate = ( shippingRates ) => {
const throwError = useThrowError();
const initiallySelectedRates = shippingRates
.map(
// the API responds with those keys.
/* eslint-disable camelcase */
( p ) => [
p.package_id,
p.shipping_rates.find( ( rate ) => rate.selected )?.rate_id,
]
/* eslint-enable */
)
// A fromEntries ponyfill, creates an object from an array of arrays.
.reduce( ( obj, [ key, val ] ) => {
obj[ key ] = val;
return obj;
}, {} );
const derivedSelectedRates = useMemo(
() =>
shippingRates
.map(
// the API responds with those keys.
/* eslint-disable camelcase */
( p ) => [
p.package_id,
p.shipping_rates.find( ( rate ) => rate.selected )
?.rate_id,
]
/* eslint-enable */
)
// A fromEntries ponyfill, creates an object from an array of arrays.
.reduce( ( obj, [ key, val ] ) => {
obj[ key ] = val;
return obj;
}, {} ),
[ shippingRates ]
);
const [ selectedShippingRates, setSelectedShipping ] = useState(
initiallySelectedRates
derivedSelectedRates
);
// useState initial state is always remembered, so even if that value changes,
// useState won't update, we're forcing it to update if the initial value changes,
// useMemo helps us not running this function when we don't need to.
useEffect( () => {
setSelectedShipping( derivedSelectedRates );
}, [ derivedSelectedRates ] );
const { selectShippingRate } = useDispatch( storeKey );
const setRate = ( newShippingRate, packageId ) => {
setSelectedShipping( {