Merge pull request #10808 from backstage/emmaindal/search-react-versioned-context

[search-react] versioned context
This commit is contained in:
Emma Indal
2022-04-15 10:42:54 +02:00
committed by GitHub
4 changed files with 30 additions and 21 deletions
+1
View File
@@ -34,6 +34,7 @@
"@backstage/plugin-search-common": "^0.3.3-next.1",
"@backstage/core-plugin-api": "^1.0.1-next.0",
"@backstage/core-app-api": "^1.0.1-next.1",
"@backstage/version-bridge": "^1.0.0",
"react-use": "^17.3.2",
"@backstage/types": "^1.0.0"
},
@@ -17,8 +17,11 @@
import { JsonObject } from '@backstage/types';
import { useApi, AnalyticsContext } from '@backstage/core-plugin-api';
import { SearchResultSet } from '@backstage/plugin-search-common';
import {
createVersionedContext,
createVersionedValueMap,
} from '@backstage/version-bridge';
import React, {
createContext,
PropsWithChildren,
useCallback,
useContext,
@@ -50,12 +53,25 @@ export type SearchContextState = {
pageCursor?: string;
};
const SearchContext = createVersionedContext<{
1: SearchContextValue;
}>('search-context');
/**
* @public
*/
export const SearchContext = createContext<SearchContextValue | undefined>(
undefined,
);
export const useSearch = () => {
const context = useContext(SearchContext);
if (!context) {
throw new Error('useSearch must be used within a SearchContextProvider');
}
const value = context.atVersion(1);
if (!value) {
throw new Error('No SearchContext v1 found');
}
return value;
};
/**
* The initial state of `SearchContextProvider`.
@@ -128,20 +144,11 @@ export const SearchContextProvider = ({
fetchPreviousPage: hasPreviousPage ? fetchPreviousPage : undefined,
};
const versionedValue = createVersionedValueMap({ 1: value });
return (
<AnalyticsContext attributes={{ searchTypes: types.sort().join(',') }}>
<SearchContext.Provider value={value} children={children} />
<SearchContext.Provider value={versionedValue} children={children} />
</AnalyticsContext>
);
};
/**
* @public
*/
export const useSearch = () => {
const context = useContext(SearchContext);
if (context === undefined) {
throw new Error('useSearch must be used within a SearchContextProvider');
}
return context;
};
+1 -5
View File
@@ -14,11 +14,7 @@
* limitations under the License.
*/
export {
SearchContextProvider,
SearchContext,
useSearch,
} from './SearchContext';
export { SearchContextProvider, useSearch } from './SearchContext';
export type { SearchContextState } from './SearchContext';
export {
SearchContextProvider as SearchContextProviderForStorybook,