From fee4ca129c18a2a64db06f801059e994e1a03104 Mon Sep 17 00:00:00 2001 From: Marin Atanasov <8436925+tyxla@users.noreply.github.com> Date: Mon, 25 Sep 2023 19:45:22 +0300 Subject: [PATCH] core-data: Fix nested property access with undefined name (#54790) * core-data: Fix nested property access with undefined name * Add a unit test --- .../core-data/src/queried-data/selectors.js | 2 +- packages/core-data/src/selectors.ts | 2 +- packages/core-data/src/test/selectors.js | 37 +++++++++++++++++++ 3 files changed, 39 insertions(+), 2 deletions(-) diff --git a/packages/core-data/src/queried-data/selectors.js b/packages/core-data/src/queried-data/selectors.js index a3e6f322274ced..562aab7ce6b79b 100644 --- a/packages/core-data/src/queried-data/selectors.js +++ b/packages/core-data/src/queried-data/selectors.js @@ -68,7 +68,7 @@ function getQueriedItemsUncached( state, query ) { const field = fields[ f ].split( '.' ); let value = item; field.forEach( ( fieldName ) => { - value = value[ fieldName ]; + value = value?.[ fieldName ]; } ); setNestedValue( filteredItem, field, value ); diff --git a/packages/core-data/src/selectors.ts b/packages/core-data/src/selectors.ts index 7d6cbeb4daeee9..34445f73d2e60a 100644 --- a/packages/core-data/src/selectors.ts +++ b/packages/core-data/src/selectors.ts @@ -344,7 +344,7 @@ export const getEntityRecord = createSelector( const field = fields[ f ].split( '.' ); let value = item; field.forEach( ( fieldName ) => { - value = value[ fieldName ]; + value = value?.[ fieldName ]; } ); setNestedValue( filteredItem, field, value ); } diff --git a/packages/core-data/src/test/selectors.js b/packages/core-data/src/test/selectors.js index 161d0af4ea5bca..5ae7a81fa144e9 100644 --- a/packages/core-data/src/test/selectors.js +++ b/packages/core-data/src/test/selectors.js @@ -135,6 +135,43 @@ describe.each( [ } ) ).toEqual( { content: 'chicken' } ); } ); + + it( 'should work well for nested fields properties', () => { + const state = deepFreeze( { + entities: { + records: { + root: { + postType: { + queriedData: { + items: { + default: { + post: { + foo: undefined, + }, + }, + }, + itemIsComplete: { + default: { + post: true, + }, + }, + queries: {}, + }, + }, + }, + }, + }, + } ); + expect( + getEntityRecord( state, 'root', 'postType', 'post', { + _fields: [ 'foo.bar' ], + } ) + ).toEqual( { + foo: { + bar: undefined, + }, + } ); + } ); } ); describe( 'hasEntityRecords', () => {