packages/core-api: make ApiProvider forward APIs from parent context

This commit is contained in:
Patrik Oldsberg
2020-06-08 12:06:24 +02:00
parent 36773f612d
commit 6567f241b5
2 changed files with 36 additions and 3 deletions
@@ -51,6 +51,35 @@ describe('ApiProvider', () => {
renderedHoc.getByText('hoc message: hello');
});
it('should provide nested access to apis', () => {
const aRef = createApiRef<string>({ id: 'a', description: '' });
const bRef = createApiRef<string>({ id: 'b', description: '' });
const MyComponent = () => {
const a = useApi(aRef);
const b = useApi(bRef);
return (
<div>
a={a} b={b}
</div>
);
};
const renderedHook = render(
<ApiProvider
apis={ApiRegistry.from([
[aRef, 'x'],
[bRef, 'y'],
])}
>
<ApiProvider apis={ApiRegistry.from([[aRef, 'z']])}>
<MyComponent />
</ApiProvider>
</ApiProvider>,
);
renderedHook.getByText('a=z b=y');
});
it('should ignore deps in prototype', () => {
// 100% coverage + happy typescript = hasOwnProperty + this atrocity
const xRef = createApiRef<number>({ id: 'x', description: '' });
+7 -3
View File
@@ -18,16 +18,20 @@ import React, { FC, createContext, useContext, ReactNode } from 'react';
import PropTypes from 'prop-types';
import { ApiRef } from './ApiRef';
import { ApiHolder, TypesToApiRefs } from './types';
import { ApiAggregator } from './ApiAggregator';
type Props = {
type ApiProviderProps = {
apis: ApiHolder;
children: ReactNode;
};
const Context = createContext<ApiHolder | undefined>(undefined);
export const ApiProvider: FC<Props> = ({ apis, children }) => {
return <Context.Provider value={apis} children={children} />;
export const ApiProvider: FC<ApiProviderProps> = ({ apis, children }) => {
const parentHolder = useContext(Context);
const holder = parentHolder ? new ApiAggregator(apis, parentHolder) : apis;
return <Context.Provider value={holder} children={children} />;
};
ApiProvider.propTypes = {