Typescript errors on stateToRoute and routeToState in stateMapping (InstantSearch Hooks routing) #5519
-
|
Hi, I'm using Algolia in combination with Contentful and Next.js. One of the pages I'm developing is an archive page with a SearchBox and several RefinementLists. Since Algolia indexes the Contentful fields with its full name (for example Following the docs, I was using stateToRoute and routeToState to transform the necessary fields. Everything works as expected, but unfortunately only when I specifically add a ts-ignore comment above both these methods. This is my InstantSearch component: And these are the Typescript errors I'm getting: I must be doing something wrong obviously, but I can't seem to figure out what. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 28 replies
-
|
This probably could be documented more clearly indeed, but the RouteState defaults to UiState, so if you transform it, you should pass the generic to InstantSearch like this: import type { SearchClient, UiState } from 'instantsearch.js';
import React from 'react';
import { InstantSearch } from 'react-instantsearch-hooks';
import { createInstantSearchRouterNext } from 'react-instantsearch-hooks-router-nextjs';
import singletonRouter from 'next/router';
type RouteState = {
q?: string;
timing?: string[];
theme?: string[];
type?: string[];
technology?: string[];
sortBy?: string;
page?: number;
};
export function App({
indexName,
searchClient,
}: {
indexName: string;
searchClient: SearchClient;
}) {
return (
<InstantSearch<UiState, RouteState>
searchClient={searchClient}
indexName={indexName}
routing={{
router: createInstantSearchRouterNext({
singletonRouter,
}),
stateMapping: {
stateToRoute(uiState) {
const indexUiState = uiState[indexName];
return {
q: indexUiState.query,
timing: indexUiState.refinementList?.timing,
theme: indexUiState.refinementList?.['fields.theme.en-US'],
type: indexUiState.refinementList?.['fields.type.en-US'],
technology:
indexUiState.refinementList?.['fields.technology.en-US'],
sortBy: indexUiState.sortBy?.split(`${indexName}_`)[1],
page: indexUiState.page,
};
},
routeToState(routeState) {
return {
[indexName]: {
query: routeState.q,
refinementList: {
timing: routeState.timing,
'fields.theme.en-US': routeState.theme,
'fields.type.en-US': routeState.type,
'fields.technology.en-US': routeState.technology,
},
page: routeState.page,
...(routeState.sortBy
? { sortBy: `${indexName}_${routeState.sortBy}` }
: {}),
},
};
},
},
}}
></InstantSearch>
);
} |
Beta Was this translation helpful? Give feedback.


This probably could be documented more clearly indeed, but the RouteState defaults to UiState, so if you transform it, you should pass the generic to InstantSearch like this: