Sharing state across pages #5316
-
Hi, I'm trying to keep the user's configuration in shared state across pages using React Context import * as React from "react";
type AlgoliaState = any | undefined;
type ContextState = { algoliaState: AlgoliaState,
setAlgoliaState: React.Dispatch<
React.SetStateAction<AlgoliaState>>,
};
const AlgoliaContext =
React.createContext<ContextState | undefined>(undefined);
interface AlgoliaProviderProps {
children: React.ReactNode;
}
const AlgoliaProvider = (props: AlgoliaProviderProps) => {
const [algoliaState, setAlgoliaState] =
React.useState<AlgoliaState>({});
const value = {algoliaState, setAlgoliaState};
return (
<AlgoliaContext.Provider value={value}>
{props.children}
</AlgoliaContext.Provider>
);
};
/**
* Hook to access the algolia context
* @return{AlgoliaState}
*/
function useAlgolia(): AlgoliaState {
const context = React.useContext(AlgoliaContext);
if (context === undefined) {
throw new Error(
"useAlgolia must be used within a AlgoliaProvider"
);
}
return {
algoliaState: context.algoliaState,
setAlgoliaState: context.setAlgoliaState,
};
}
export {AlgoliaProvider, useAlgolia}; My components use instantsearch like this, a child of the ...
const {algoliaState, setAlgoliaState} = useAlgolia();
...
<InstantSearch
searchClient={searchClient}
indexName="my_index"
initialUiState={algoliaState}
onStateChange={(searchState) => {
setAlgoliaState(searchState.uiState);
}}
>
... Then I use multiple Algolia components to filter ( I'm trying to get the list of hits in different pages, but my other pages don't take into account the configuration (say I checked a category or something like this) How do you share the instantsearch configuration across multiple pages? Thanks a lot of the help 😇 |
Beta Was this translation helpful? Give feedback.
Replies: 0 comments 1 reply
-
It highly depends on your app configuration. Wrapping your page in the For instance, for function Page() {
useRefinementList({ attribute: 'brand' });
// ...
}
function App(props) {
return (
<InstantSearch {...props}>
<Page />
</InstantSearch>
);
} We're currently working on the docs to make this more visible. |
Beta Was this translation helpful? Give feedback.
It highly depends on your app configuration. Wrapping your page in the
<InstantSearch>
component should work, but you should also have the widgets responsible for the UI state mounted on each page.For instance, for
initialUiState.indexName.refinementList.brand
to be effective, you need to mount the<RefinementList attribute="brand" />
on your page. This is a limitation of InstantSearch so that the UI state is taken into account. If you don't want to display any refinements, you can mount a "virtual widget", which means calling the Hook without rendering anything: