Routing URLs Not Working: TypeError: Cannot read property 'search' of undefined

I’m trying to change the URL based on the search/refinements and I was referring to the React Routing URLs Docs here

All my search results/refinements/searchboxes are contained in my component called <SearchGrid/>. This is imported from search.js. This is how I’ve set up the routing currently:

import algoliasearch from "algoliasearch/lite"
import {
  InstantSearch,
  Hits,
  Highlight,
  connectStateResults,
  SearchBox,
  RefinementList,
  PoweredBy,
  ClearRefinements,
  MenuSelect,
} from "react-instantsearch-dom"
import React, { useState } from "react"
import qs from "qs"

const DEBOUNCE_TIME = 400

const searchClient = algoliasearch(
  process.env.GATSBY_ALGOLIA_APP_ID,
  process.env.GATSBY_ALGOLIA_SEARCH_KEY
)

const createURL = state => `?${qs.stringify(state)}`

const searchStateToUrl = ({ location }, searchState) =>
  searchState ? `${location.pathname}${createURL(searchState)}` : ""

const urlToSearchState = ({ search }) => qs.parse(search.slice(1))

//Search Grid

const SearchGrid = ({ location, history }) => {
  
  const [searchState, setSearchState] = useState(urlToSearchState(location))
  const [debouncedSetState, setDebouncedSetState] = useState(null)

  const onSearchStateChange = updatedSearchState => {
    clearTimeout(debouncedSetState)

    setDebouncedSetState(
      setTimeout(() => {
        history.pushState(
          updatedSearchState,
          null,
          searchStateToUrl(updatedSearchState)
        )
      }, DEBOUNCE_TIME)
    )

    setSearchState(updatedSearchState)
  }

  return (
    <div className="bg-gray-900 pattern ">
      <div class="sticky top-0 ">
        <InstantSearch
          searchClient={searchClient}
          indexName="archives"
          searchState={searchState}
          onSearchStateChange={onSearchStateChange}
          createURL={createURL}
        >
//Other Code Follows

This gives me the following error:

TypeError: Cannot read property 'search' of undefined
urlToSearchState
D:/Gatsby/archives/src/components/search/search.js:32
  29 | const searchStateToUrl = ({ location }, searchState) =>
  30 |   searchState ? `${location.pathname}${createURL(searchState)}` : '';
  31 | 
> 32 | const urlToSearchState = ({ search }) => qs.parse(search.slice(1));
  33 | 
  34 | 
  35 | //Search Grid

The full search.js file is uploaded here.

How can I fix this? I would like to be able to just change the url based on the search, as the feature seems to be.

I was getting this error as well. My issue was that when I was passing ‘location’ to urlToSearchState, ‘location’ was undefined. That might your problem as well in your code as well here:
const [searchState, setSearchState] = useState(urlToSearchState(location))
It looks like you are destructuring location from props. I would make sure it is coming through as expected.