Skip to content

Commit

Permalink
EntityProvider: Avoid remounts and simplify (#61882)
Browse files Browse the repository at this point in the history
Co-authored-by: youknowriad <youknowriad@git.wordpress.org>
Co-authored-by: stokesman <presstoke@git.wordpress.org>
  • Loading branch information
3 people committed May 22, 2024
1 parent 4a16db2 commit dfae29a
Showing 1 changed file with 19 additions and 36 deletions.
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

1 comment on commit dfae29a

@github-actions
Copy link

Choose a reason for hiding this comment

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

Flaky tests detected in dfae29a.
Some tests passed with failed attempts. The failures may not be related to this commit but are still reported for visibility. See the documentation for more information.

🔍 Workflow run URL: https://github.com/WordPress/gutenberg/actions/runs/9199301464
📝 Reported issues:

Please sign in to comment.