Reputation: 51
I am using next.js and currently I have an input on my homepage that allows a user to enter a search. I made it so that when a user submits their search on the homepage, it takes me to the /search page which uses algolia's instantsearch with the search already applied (to do this, I used routing={true} on my InstantSearch component).
The issue I have comes from the browser history. So when a user types "phone" on the home-page, it goes from "/" -> "/search?search=phone" -> "/search?<index_name>%5Bquery%5D=phone". Now when the user clicks the back button on the browser, it takes them to "/search?search=phone" which isn't actually connected to algolia, so it just shows the /search page with all the results in my index. How can I have it so that the user is instantly taken to "/search?<index_name>%5Bquery%5D=phone" instead of "/search?search=phone" so that when they press back on the browser, it takes them to the homepage "/"?
On my homepage, I have the following event listener
import { useRouter } from 'next/navigation';
const router = useRouter();
const handleSearch = (e) => {
e.preventDefault();
router.push(`/search?search=${encodeURIComponent(query)}`)
};
On my search page.tsx, I have:
import { useSearchParams } from 'next/navigation';
const SearchPage = () => {
const searchParams = useSearchParams();
const search = searchParams.get('search');
return (
<InstantSearch
searchClient={searchClient}
indexName={indexName}
initialUiState={{
[indexName]: {
query: search,
},
}}
future={{
preserveSharedStateOnUnmount: true,
}}
routing={true}
>
<SearchComponent />
</InstantSearch>
);
};
Upvotes: 2
Views: 377