I'm setting up React Instantsearch but because of SEO features I want to listen to a query string on pageload and then set it in the SearchBox. I've tried all the examples in documentation but I can't get it work.
The only way I can control the state of the SearchBox is through the queryHook but using that I can't set the query on pageload — only whenever the SearchBox is being modified.
My code looks like this right now. I want to set the "search" variable to be set on pageload if there is an query parameter available.
import React from 'react'
import { Link } from 'gatsby'
import algoliasearch from 'algoliasearch/lite';
import {
InstantSearch,
InfiniteHits,
SearchBox,
Configure,
} from 'react-instantsearch-hooks-web';
export default function Search({ location }) {
const [search, setSearch] = React.useState("")
const params = new URLSearchParams(location.search);
const searchClient = algoliasearch(
'...',
'...'
);
React.useEffect(() => {
const searchTerm = params.get("searchTerm");
if (searchTerm?.length > 0) setSearch(searchTerm)
}, [params])
return (
<>
<Layout>
<div id="Contact">
<div className="contactWrapper">
<section className="section">
<div className="searchWrapper">
<InstantSearch
indexName="All Pages"
searchClient={searchClient}
>
<div className="searchFieldWrapper">
<Configure hitsPerPage={20} />
<SearchBox
placeholder={"Vad söker du?"}
/>
</div>
<div className="searchResultWrapper">
<InfiniteHits hitComponent={Hit} />
</div>
</InstantSearch>
</div>
</section>
</div>
</div>
</Layout>
</>
)
}
function Hit(props) {
return (
<div className="box">
<Link to={props.hit.url}>
<div className="image">
<img src={props.hit.image} alt={props.hit.name} />
</div>
<div className="title">
{props.hit.title.split(" | ")[0].split(" - ")[0].split(" — ")[0]}
</div>
</Link>
</div>
);
}