[react-instantsearch-hooks] controlled mode #5314
Answered
by
louis030195
louis030195
asked this question in
Q&A
-
Hi, I'm trying to keep the user's configuration in shared state 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 component, a child of the ...
const {algoliaState, setAlgoliaState} = useAlgolia();
...
<InstantSearch
searchClient={searchClient}
indexName="my_index"
initialUiState={algoliaState}
onStateChange={(searchState) => {
setAlgoliaState(searchState);
}}
>
... Then I use multiple Algolia components to filter ( When I use controlled state, the state properly change but not in the children components ( So concretely I'd like that when the user adds some refinement and change page, when he come back to this page he still has his refinements. What am I doing wrong? Thanks a lot of the help 😇 |
Beta Was this translation helpful? Give feedback.
Answered by
louis030195
May 29, 2022
Replies: 0 comments 1 reply
-
Oops: onStateChange={(searchState) => {
setAlgoliaState(searchState);
}} Should be onStateChange={(searchState) => {
setAlgoliaState(searchState.uiState);
}} Problem solved |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
louis030195
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Oops:
Should be
Problem solved