From c44891a4a2a1ced4dc583cd0423b0e5bdd9f6eda Mon Sep 17 00:00:00 2001 From: Valeriy Date: Sat, 27 Jul 2019 22:23:09 +0300 Subject: [PATCH] fix: search page is populated with relevant results when search bar is submitted --- .../components/search/WithInstantSearch.js | 28 ++++++++++++++----- .../components/search/searchBar/SearchBar.js | 2 +- 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/client/src/components/search/WithInstantSearch.js b/client/src/components/search/WithInstantSearch.js index 366722d145..8ffb443420 100644 --- a/client/src/components/search/WithInstantSearch.js +++ b/client/src/components/search/WithInstantSearch.js @@ -4,6 +4,7 @@ import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { InstantSearch, Configure } from 'react-instantsearch-dom'; import qs from 'query-string'; +import { navigate } from 'gatsby'; import { isSearchDropdownEnabledSelector, @@ -14,6 +15,8 @@ import { import { createSelector } from 'reselect'; +const DEBOUNCE_TIME = 400; + const propTypes = { children: PropTypes.any, isDropdownEnabled: PropTypes.bool, @@ -56,7 +59,20 @@ class InstantSearchRoot extends Component { if (location !== prevProps.location) { const { query, updateSearchQuery } = this.props; if (this.isSearchPage()) { - this.setQueryFromURL(); + if ( + location.state && + typeof location.state === 'object' && + location.state.hasOwnProperty('query') + ) { + updateSearchQuery(location.state.query); + } else if (location.search) { + this.setQueryFromURL(); + } else { + navigate(searchStateToUrl(this.props.location, query), { + state: { query }, + replace: true + }); + } } else if (query) { updateSearchQuery(''); } @@ -90,13 +106,11 @@ class InstantSearchRoot extends Component { this.debouncedSetState = setTimeout(() => { if (this.isSearchPage()) { - window.history.pushState( - { query }, - null, - searchStateToUrl(this.props.location, query) - ); + navigate(searchStateToUrl(this.props.location, query), { + state: { query } + }); } - }, 400); + }, DEBOUNCE_TIME); } }; diff --git a/client/src/components/search/searchBar/SearchBar.js b/client/src/components/search/searchBar/SearchBar.js index 61c819c19f..4aeefc6e44 100644 --- a/client/src/components/search/searchBar/SearchBar.js +++ b/client/src/components/search/searchBar/SearchBar.js @@ -85,7 +85,7 @@ class SearchBar extends Component { if (query) { updateSearchQuery(query); } - return navigate(`/search${query ? `?query=${query}` : ''}`); + return navigate('/search'); } render() {