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

EntityProvider: Avoid remounts and simplify #61882

Merged
merged 1 commit into from
May 22, 2024
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: 19 additions & 36 deletions packages/core-data/src/entity-provider.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,39 +20,7 @@ import { updateFootnotesFromMeta } from './footnotes';

const EMPTY_ARRAY = [];

/**
* Internal dependencies
*/
import { rootEntitiesConfig, additionalEntityConfigLoaders } from './entities';

const entityContexts = {
...rootEntitiesConfig.reduce( ( acc, loader ) => {
if ( ! acc[ loader.kind ] ) {
acc[ loader.kind ] = {};
}
acc[ loader.kind ][ loader.name ] = {
context: createContext( undefined ),
};
return acc;
}, {} ),
...additionalEntityConfigLoaders.reduce( ( acc, loader ) => {
acc[ loader.kind ] = {};
return acc;
}, {} ),
};
const getEntityContext = ( kind, name ) => {
if ( ! entityContexts[ kind ] ) {
throw new Error( `Missing entity config for kind: ${ kind }.` );
}

if ( ! entityContexts[ kind ][ name ] ) {
entityContexts[ kind ][ name ] = {
context: createContext( undefined ),
};
}

return entityContexts[ kind ][ name ].context;
};
const EntityContext = createContext( {} );

/**
* Context provider component for providing
Expand All @@ -68,8 +36,22 @@ const getEntityContext = ( kind, name ) => {
* the entity's context provider.
*/
export default function EntityProvider( { kind, type: name, id, children } ) {
const Provider = getEntityContext( kind, name ).Provider;
return <Provider value={ id }>{ children }</Provider>;
const parent = useContext( EntityContext );
const childContext = useMemo(
() => ( {
...parent,
[ kind ]: {
...parent?.[ kind ],
[ name ]: id,
},
} ),
[ parent, kind, name, id ]
);
return (
<EntityContext.Provider value={ childContext }>
{ children }
</EntityContext.Provider>
);
}

/**
Expand All @@ -80,7 +62,8 @@ export default function EntityProvider( { kind, type: name, id, children } ) {
* @param {string} name The entity name.
*/
export function useEntityId( kind, name ) {
return useContext( getEntityContext( kind, name ) );
const context = useContext( EntityContext );
return context?.[ kind ]?.[ name ];
}

/**
Expand Down
Loading