Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

core-data: Fix nested property access with undefined name #54790

Merged
merged 2 commits into from
Sep 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/core-data/src/queried-data/selectors.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 );
Expand Down
2 changes: 1 addition & 1 deletion packages/core-data/src/selectors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 ];
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could be nice to abort early when value becomes undefined. Also, this can be a good use of reduce:

const value = fields.reduce( ( v, f ) => v?.[ f ], item );

But the early abort probably requires a for loop with break anyway.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree, but FWIW I opted for brevity here. And I think we no longer need to abort early since we're covering undefined with the optional chaining.

} );
setNestedValue( filteredItem, field, value );
}
Expand Down
37 changes: 37 additions & 0 deletions packages/core-data/src/test/selectors.js
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down