Skip to content
Merged
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
55 changes: 38 additions & 17 deletions packages/core-data/src/reducer.js
Original file line number Diff line number Diff line change
Expand Up @@ -418,7 +418,29 @@ export function entitiesConfig( state = rootEntitiesConfig, action ) {
export const entities = ( state = {}, action ) => {
const newConfig = entitiesConfig( state.config, action );

// Generates a dynamic reducer for the entities.
// Generates a reducer for the entities nested by `kind` and `name`.
// A config array with shape:
// ```
// [
// { kind: 'taxonomy', name: 'category' },
// { kind: 'taxonomy', name: 'post_tag' },
// { kind: 'postType', name: 'post' },
// { kind: 'postType', name: 'page' },
// ]
// ```
// generates a reducer for state tree with shape:
// ```
// {
// taxonomy: {
// category,
// post_tag,
// },
// postType: {
// post,
// page,
// },
// }
// ```
let entitiesDataReducer = state.reducer;
if ( ! entitiesDataReducer || newConfig !== state.config ) {
const entitiesByKind = newConfig.reduce( ( acc, record ) => {
Expand All @@ -431,22 +453,21 @@ export const entities = ( state = {}, action ) => {
}, {} );

entitiesDataReducer = combineReducers(
Object.entries( entitiesByKind ).reduce(
( memo, [ kind, subEntities ] ) => {
const kindReducer = combineReducers(
subEntities.reduce(
( kindMemo, entityConfig ) => ( {
...kindMemo,
[ entityConfig.name ]: entity( entityConfig ),
} ),
{}
)
);

memo[ kind ] = kindReducer;
return memo;
},
{}
Object.fromEntries(
Object.entries( entitiesByKind ).map(
( [ kind, subEntities ] ) => {
const kindReducer = combineReducers(
Object.fromEntries(
subEntities.map( ( entityConfig ) => [
entityConfig.name,
entity( entityConfig ),
] )
)
);

return [ kind, kindReducer ];
}
)
)
);
}
Expand Down
Loading