Fixes regression with payment method validation (https://github.com/woocommerce/woocommerce-blocks/pull/2450)

* add typedefs for store notice context

* improve useStoreNotices hook so returned interfaces are fairly constant

* fix dependencies, defaults, and add types

* fix dependencies

* fix dependencies

* improve functions exposed on validation context so they are more constant

* fixing dependencies

* normalize tokenId to string everywhere

Assuming the token is a number is a bad idea because it is feasible that source for some payment methods could be a string. Also when retrieved as an input value, the id will be a string anyways.
This commit is contained in:
Darren Ethier 2020-05-10 19:41:10 -04:00 committed by GitHub
parent ea3d817db1
commit e7781ba407
12 changed files with 195 additions and 110 deletions

View File

@ -64,7 +64,7 @@ const PaymentMethods = () => {
...paymentMethodInterface
} = usePaymentMethodInterface();
const currentPaymentMethodInterface = useRef( paymentMethodInterface );
const [ selectedToken, setSelectedToken ] = useState( 0 );
const [ selectedToken, setSelectedToken ] = useState( '0' );
const { noticeContexts } = useEmitResponse();
const { removeNotice } = useStoreNotices();
@ -146,7 +146,7 @@ const PaymentMethods = () => {
);
return Object.keys( customerPaymentMethods ).length > 0 &&
selectedToken !== 0
selectedToken !== '0'
? renderedSavedPaymentOptions
: renderedTabsAndSavedPaymentOptions;
};

View File

@ -20,7 +20,7 @@ import RadioControl from '@woocommerce/base-components/radio-control';
*/
const getCcOrEcheckPaymentMethodOption = ( { method, expires, tokenId } ) => {
return {
value: tokenId,
value: tokenId + '',
label: sprintf(
__(
'%1$s ending in %2$s (expires %3$s)',
@ -43,7 +43,7 @@ const getCcOrEcheckPaymentMethodOption = ( { method, expires, tokenId } ) => {
*/
const getDefaultPaymentMethodOptions = ( { method, tokenId } ) => {
return {
value: tokenId,
value: tokenId + '',
label: sprintf(
__( 'Saved token for %s', 'woo-gutenberg-products-block' ),
method.gateway
@ -59,7 +59,7 @@ const SavedPaymentMethodOptions = ( { onSelect } ) => {
customerPaymentMethods,
activePaymentMethod,
} = usePaymentMethodDataContext();
const [ selectedToken, setSelectedToken ] = useState( null );
const [ selectedToken, setSelectedToken ] = useState( '' );
/**
* @type {Object} Options
@ -77,11 +77,9 @@ const SavedPaymentMethodOptions = ( { onSelect } ) => {
paymentMethods.map( ( paymentMethod ) => {
if (
paymentMethod.is_default &&
selectedToken === null
selectedToken === ''
) {
setSelectedToken(
parseInt( paymentMethod.tokenId, 10 )
);
setSelectedToken( paymentMethod.tokenId + '' );
}
return type === 'cc' || type === 'echeck'
? getCcOrEcheckPaymentMethodOption(
@ -96,7 +94,7 @@ const SavedPaymentMethodOptions = ( { onSelect } ) => {
} );
currentOptions.current = options;
currentOptions.current.push( {
value: 0,
value: '0',
label: __(
'Use a new payment method',
'woo-gutenberg-product-blocks'
@ -117,10 +115,10 @@ const SavedPaymentMethodOptions = ( { onSelect } ) => {
} else {
setPaymentStatus().started();
}
setSelectedToken( parseInt( token, 10 ) );
onSelect( parseInt( token, 10 ) );
setSelectedToken( token );
onSelect( token );
},
[ setSelectedToken, setPaymentStatus, onSelect ]
[ setSelectedToken, setPaymentStatus, onSelect, activePaymentMethod ]
);
useEffect( () => {
if ( selectedToken && currentOptions.current.length > 0 ) {
@ -129,7 +127,7 @@ const SavedPaymentMethodOptions = ( { onSelect } ) => {
}, [ selectedToken, updateToken ] );
// In the editor, show `Use a new payment method` option as selected.
const selectedOption = isEditor ? 0 : selectedToken;
const selectedOption = isEditor ? '0' : selectedToken + '';
return currentOptions.current.length > 0 ? (
<RadioControl
id={ 'wc-payment-method-stripe-saved-tokens' }

View File

@ -173,7 +173,7 @@ export const CheckoutStateProvider = ( {
// emit events.
useEffect( () => {
const { status } = checkoutState;
const status = checkoutState.status;
if ( status === STATUS.BEFORE_PROCESSING ) {
removeNotices( 'error' );
emitEvent(
@ -196,7 +196,13 @@ export const CheckoutStateProvider = ( {
}
} );
}
}, [ checkoutState.status, setValidationErrors ] );
}, [
checkoutState.status,
setValidationErrors,
addErrorNotice,
removeNotices,
dispatch,
] );
useEffect( () => {
if ( checkoutState.status === STATUS.AFTER_PROCESSING ) {
@ -292,6 +298,10 @@ export const CheckoutStateProvider = ( {
checkoutState.customerNote,
checkoutState.processingResponse,
dispatchActions,
addErrorNotice,
isErrorResponse,
isFailResponse,
isSuccessResponse,
] );
const onSubmit = () => {

View File

@ -100,6 +100,7 @@ const CheckoutProcessor = () => {
checkoutIsProcessing,
checkoutIsBeforeProcessing,
expressPaymentMethodActive,
dispatchActions,
] );
const paidAndWithoutErrors =
@ -234,6 +235,8 @@ const CheckoutProcessor = () => {
paymentMethodId,
paymentMethodData,
cartNeedsPayment,
receiveCart,
dispatchActions,
] );
// redirect when checkout is complete and there is a redirect url.
useEffect( () => {

View File

@ -170,47 +170,6 @@ export const PaymentMethodDataProvider = ( { children } ) => {
[ paymentData.currentStatus ]
);
// flip payment to processing if checkout processing is complete, there are
// no errors, and payment status is started.
useEffect( () => {
if (
checkoutIsProcessing &&
! checkoutHasError &&
! checkoutIsCalculating &&
! currentStatus.isFinished
) {
setPaymentStatus().processing();
}
}, [
checkoutIsProcessing,
checkoutHasError,
checkoutIsCalculating,
currentStatus.isFinished,
] );
// when checkout is returned to idle, set payment status to pristine.
useEffect( () => {
dispatch( statusOnly( PRISTINE ) );
}, [ checkoutIsIdle ] );
// set initial active payment method if it's undefined.
useEffect( () => {
const paymentMethodKeys = Object.keys( paymentData.paymentMethods );
if (
paymentMethodsInitialized &&
! activePaymentMethod &&
paymentMethodKeys.length > 0
) {
setActivePaymentMethod(
Object.keys( paymentData.paymentMethods )[ 0 ]
);
}
}, [
activePaymentMethod,
paymentMethodsInitialized,
paymentData.paymentMethods,
] );
/**
* @type {PaymentStatusDispatch}
*/
@ -267,9 +226,52 @@ export const PaymentMethodDataProvider = ( { children } ) => {
);
},
} ),
[ dispatch ]
[ dispatch, setBillingData, setShippingAddress ]
);
// flip payment to processing if checkout processing is complete, there are
// no errors, and payment status is started.
useEffect( () => {
if (
checkoutIsProcessing &&
! checkoutHasError &&
! checkoutIsCalculating &&
! currentStatus.isFinished
) {
setPaymentStatus().processing();
}
}, [
checkoutIsProcessing,
checkoutHasError,
checkoutIsCalculating,
currentStatus.isFinished,
setPaymentStatus,
] );
// when checkout is returned to idle, set payment status to pristine.
useEffect( () => {
dispatch( statusOnly( PRISTINE ) );
}, [ checkoutIsIdle ] );
// set initial active payment method if it's undefined.
useEffect( () => {
const paymentMethodKeys = Object.keys( paymentData.paymentMethods );
if (
paymentMethodsInitialized &&
! activePaymentMethod &&
paymentMethodKeys.length > 0
) {
setActivePaymentMethod(
Object.keys( paymentData.paymentMethods )[ 0 ]
);
}
}, [
activePaymentMethod,
paymentMethodsInitialized,
paymentData.paymentMethods,
setActivePaymentMethod,
] );
// emit events.
useEffect( () => {
// Note: the nature of this event emitter is that it will bail on any
@ -323,7 +325,17 @@ export const PaymentMethodDataProvider = ( { children } ) => {
}
} );
}
}, [ currentStatus.isProcessing, setValidationErrors, setPaymentStatus ] );
}, [
currentStatus.isProcessing,
setValidationErrors,
setPaymentStatus,
removeNotice,
noticeContexts.PAYMENTS,
isSuccessResponse,
isFailResponse,
isErrorResponse,
addErrorNotice,
] );
/**
* @type {PaymentMethodDataContext}

View File

@ -81,19 +81,22 @@ export const ValidationContextProvider = ( { children } ) => {
* @param {string} property The name of the property to clear if exists in
* validation error state.
*/
const clearValidationError = ( property ) => {
const clearValidationError = useCallback( ( property ) => {
updateValidationErrors( ( prevErrors ) => {
if ( ! prevErrors[ property ] ) {
return prevErrors;
}
return omit( prevErrors, [ property ] );
} );
};
}, [] );
/**
* Clears the entire validation error state.
*/
const clearAllValidationErrors = () => void updateValidationErrors( {} );
const clearAllValidationErrors = useCallback(
() => void updateValidationErrors( {} ),
[]
);
/**
* Used to record new validation errors in the state.
@ -132,7 +135,7 @@ export const ValidationContextProvider = ( { children } ) => {
* @param {string} property The name of the property to update.
* @param {Object} newError New validation error object.
*/
const updateValidationError = ( property, newError ) => {
const updateValidationError = useCallback( ( property, newError ) => {
updateValidationErrors( ( prevErrors ) => {
if ( ! prevErrors.hasOwnProperty( property ) ) {
return prevErrors;
@ -148,7 +151,7 @@ export const ValidationContextProvider = ( { children } ) => {
[ property ]: updatedError,
};
} );
};
}, [] );
/**
* Given a property name and if an associated error exists, it sets its
@ -157,10 +160,13 @@ export const ValidationContextProvider = ( { children } ) => {
* @param {string} property The name of the property to set the `hidden`
* value to true.
*/
const hideValidationError = ( property ) =>
void updateValidationError( property, {
hidden: true,
} );
const hideValidationError = useCallback(
( property ) =>
void updateValidationError( property, {
hidden: true,
} ),
[ updateValidationError ]
);
/**
* Given a property name and if an associated error exists, it sets its
@ -169,36 +175,42 @@ export const ValidationContextProvider = ( { children } ) => {
* @param {string} property The name of the property to set the `hidden`
* value to false.
*/
const showValidationError = ( property ) =>
void updateValidationError( property, {
hidden: false,
} );
const showValidationError = useCallback(
( property ) =>
void updateValidationError( property, {
hidden: false,
} ),
[ updateValidationError ]
);
/**
* Sets the `hidden` value of all errors to `false`.
*/
const showAllValidationErrors = () =>
void updateValidationErrors( ( prevErrors ) => {
const updatedErrors = {};
const showAllValidationErrors = useCallback(
() =>
void updateValidationErrors( ( prevErrors ) => {
const updatedErrors = {};
Object.keys( prevErrors ).forEach( ( property ) => {
if ( prevErrors[ property ].hidden ) {
updatedErrors[ property ] = {
...prevErrors[ property ],
hidden: false,
};
Object.keys( prevErrors ).forEach( ( property ) => {
if ( prevErrors[ property ].hidden ) {
updatedErrors[ property ] = {
...prevErrors[ property ],
hidden: false,
};
}
} );
if ( Object.values( updatedErrors ).length === 0 ) {
return prevErrors;
}
} );
if ( Object.values( updatedErrors ).length === 0 ) {
return prevErrors;
}
return {
...prevErrors,
...updatedErrors,
};
} );
return {
...prevErrors,
...updatedErrors,
};
} ),
[]
);
const context = {
getValidationError,

View File

@ -9,14 +9,23 @@ import {
SnackbarNoticesContainer,
} from '@woocommerce/base-components/store-notices-container';
/**
* @typedef {import('@woocommerce/type-defs/contexts').NoticeContext} NoticeContext
*/
const StoreNoticesContext = createContext( {
notices: [],
createNotice: ( status, text, props ) => void { status, text, props },
createSnackBarNotice: () => void null,
createSnackbarNotice: ( content, options ) => void { content, options },
removeNotice: ( id, ctxt ) => void { id, ctxt },
context: 'wc/core',
} );
/**
* Returns the notices context values.
*
* @return {NoticeContext} The notice context value from the notice context.
*/
export const useStoreNoticesContext = () => {
return useContext( StoreNoticesContext );
};
@ -53,7 +62,7 @@ export const StoreNoticesProvider = ( {
( id, ctxt = context ) => {
removeNotice( id, ctxt );
},
[ createNotice, context ]
[ removeNotice, context ]
);
const createSnackbarNotice = useCallback(

View File

@ -2,7 +2,7 @@
* External dependencies
*/
import { useStoreNoticesContext } from '@woocommerce/base-context';
import { useMemo } from '@wordpress/element';
import { useMemo, useRef, useEffect } from '@wordpress/element';
export const useStoreNotices = () => {
const {
@ -11,8 +11,36 @@ export const useStoreNotices = () => {
removeNotice,
createSnackbarNotice,
} = useStoreNoticesContext();
// Added to a ref so the surface for notices doesn't change frequently
// and thus can be used as dependencies on effects.
const currentNotices = useRef( notices );
// Update notices ref whenever they change
useEffect( () => {
currentNotices.current = notices;
}, [ notices ] );
const noticesApi = useMemo(
() => ( {
hasNoticesOfType: ( type ) => {
return currentNotices.current.some(
( notice ) => notice.type === type
);
},
removeNotices: ( status = null ) => {
currentNotices.current.map( ( notice ) => {
if ( status === null || notice.status === status ) {
removeNotice( notice.id );
}
return true;
} );
},
removeNotice,
} ),
[ removeNotice ]
);
const noticeCreators = useMemo(
() => ( {
addDefaultNotice: ( text, noticeProps = {} ) =>
void createNotice( 'default', text, {
@ -34,27 +62,16 @@ export const useStoreNotices = () => {
void createNotice( 'success', text, {
...noticeProps,
} ),
hasNoticesOfType: ( type ) => {
return notices.some( ( notice ) => notice.type === type );
},
removeNotices: ( status = null ) => {
notices.map( ( notice ) => {
if ( status === null || notice.status === status ) {
removeNotice( notice.id );
}
return true;
} );
},
removeNotice,
addSnackbarNotice: ( text, noticeProps = {} ) => {
createSnackbarNotice( text, noticeProps );
},
} ),
[ createNotice, createSnackbarNotice, notices ]
[ createNotice, createSnackbarNotice ]
);
return {
notices,
...noticesApi,
...noticeCreators,
};
};

View File

@ -50,7 +50,7 @@ const CreditCardComponent = ( {
if ( paymentEvent.error ) {
onStripeError( paymentEvent );
}
setSourceId( 0 );
setSourceId( '0' );
};
const renderedCardElement = getStripeServerData().inline_cc_form ? (
<InlineCard

View File

@ -84,7 +84,7 @@ export const usePaymentProcessing = (
};
}
// use token if it's set.
if ( parseInt( sourceId, 10 ) !== 0 ) {
if ( sourceId !== '' && sourceId !== '0' ) {
return {
type: emitResponse.responseTypes.SUCCESS,
meta: {

View File

@ -8,7 +8,7 @@ export const previewSavedPaymentMethods = {
},
expires: '12/20',
is_default: false,
tokenId: 1,
tokenId: '1',
},
],
};

View File

@ -305,4 +305,28 @@
* @property {boolean} hasValidationErrors True if there is at least one error.
*/
/**
* @typedef StoreNoticeObject
*
* @property {string} type The type of notice.
* @property {string} status The status of the notice.
* @property {string} id The id of the notice.
*/
/**
* @typedef NoticeContext
*
* @property {Array<StoreNoticeObject>} notices An array of notice
* objects.
* @property {function(string,string,any):undefined} createNotice Creates a notice for the
* given arguments.
* @property {function(string, any):undefined} createSnackbarNotice Creates a snackbar notice
* type.
* @property {function(string,string=):undefined} removeNotice Removes a notice with the
* given id and context
* @property {string} context The current context
* identifier for the notice
* provider
*/
export {};