Add useProductMetadata hook (#42961)

* Add useProductMetadata hook to perform update in multiple meta entries at same time

* Update type to string

* Add test

* Remove unused parameters
This commit is contained in:
Nathan Silveira 2023-12-19 17:17:08 -03:00 committed by GitHub
parent b04c45ee5e
commit ddd877441c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 98 additions and 0 deletions

View File

@ -0,0 +1,4 @@
Significance: minor
Type: add
Add useProductMetadata hook to perform update in multiple meta entries at same time

View File

@ -4,3 +4,4 @@ export { useVariationsOrder as __experimentalUseVariationsOrder } from './use-va
export { useCurrencyInputProps as __experimentalUseCurrencyInputProps } from './use-currency-input-props';
export { useVariationSwitcher as __experimentalUseVariationSwitcher } from './use-variation-switcher';
export { default as __experimentalUseProductEntityProp } from './use-product-entity-prop';
export { default as __experimentalUseProductMetadata } from './use-product-metadata';

View File

@ -0,0 +1,63 @@
/**
* External dependencies
*/
import { renderHook } from '@testing-library/react-hooks';
/**
* Internal dependencies
*/
import useProductMetadata from '../use-product-metadata';
const mockFnMetadataProp = jest.fn();
jest.mock( '@wordpress/core-data', () => ( {
useEntityProp: jest.fn().mockImplementation( () => {
return [
[
{
key: 'field1',
value: 'value1',
},
{
key: 'field2',
value: 'value1',
},
{
key: 'existing_field',
value: 'value1',
},
],
mockFnMetadataProp,
];
} ),
} ) );
describe( 'useProductMetadata', () => {
it( 'should update all the metadata with new values and not replace existing fields', async () => {
const { updateMetadata } = renderHook( () => useProductMetadata() )
.result.current;
updateMetadata( [
{
key: 'field1',
value: 'value2',
},
{
key: 'field2',
value: 'value2',
},
] );
expect( mockFnMetadataProp ).toHaveBeenCalledWith( [
{
key: 'existing_field',
value: 'value1',
},
{
key: 'field1',
value: 'value2',
},
{
key: 'field2',
value: 'value2',
},
] );
} );
} );

View File

@ -0,0 +1,30 @@
/**
* External dependencies
*/
import { useEntityProp } from '@wordpress/core-data';
/**
* Internal dependencies
*/
import { Metadata } from '../types';
function useProductMetadata( postType?: string ) {
const [ metadata, setMetadata ] = useEntityProp< Metadata< string >[] >(
'postType',
postType || 'product',
'meta_data'
);
return {
updateMetadata: ( entries: Metadata< string >[] ) => {
setMetadata( [
...metadata.filter(
( item ) =>
entries.findIndex( ( e ) => e.key === item.key ) === -1
),
...entries,
] );
},
};
}
export default useProductMetadata;