Skip to content

Commit

Permalink
fix(menu): prevent error on stale search (#3934)
Browse files Browse the repository at this point in the history
* fix(menu): prevent error on stale search

If a menu is added while the search is being stale, we will  recieve undefined (currently an error), so we can not fetch `.data` from it.

requires algolia/algoliasearch-helper-js#720

* test: add a test declaring the use case with wrong helper state
  • Loading branch information
Haroenv committed Oct 23, 2019
1 parent 0d4b49b commit 5f9e138
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
41 changes: 40 additions & 1 deletion src/connectors/menu/__tests__/connectMenu-test.js
Expand Up @@ -2,7 +2,7 @@ import jsHelper, {
SearchResults,
SearchParameters,
} from 'algoliasearch-helper';

import { createSingleSearchResponse } from '../../../../test/mock/createAPIResponse';
import connectMenu from '../connectMenu';

describe('connectMenu', () => {
Expand Down Expand Up @@ -266,6 +266,45 @@ See documentation: https://www.algolia.com/doc/api-reference/widgets/menu/js/#co
);
});

it('returns empty items if the facet is not declared', () => {
const widget = makeWidget({
attribute: 'category',
});

// note that the helper is called with empty search parameters
// which means this can only happen in a stale search situation
// when this widget gets mounted
const helper = jsHelper({}, '', {});

widget.render({
results: new SearchResults(helper.state, [
createSingleSearchResponse({
hits: [],
facets: {
category: {
Decoration: 880,
},
},
}),
createSingleSearchResponse({
facets: {
category: {
Decoration: 880,
Outdoor: 47,
},
},
}),
]),
state: helper.state,
helper,
});

expect(rendering).toHaveBeenLastCalledWith(
expect.objectContaining({ items: [] }),
false
);
});

it('provides the correct transformed facet values', () => {
const widget = makeWidget({
attribute: 'category',
Expand Down
4 changes: 3 additions & 1 deletion src/connectors/menu/connectMenu.js
Expand Up @@ -190,8 +190,10 @@ export default function connectMenu(renderFn, unmountFn = noop) {
},

render({ results, instantSearchInstance }) {
const facetValues = results.getFacetValues(attribute, { sortBy });
const facetItems =
results.getFacetValues(attribute, { sortBy }).data || [];
facetValues && facetValues.data ? facetValues.data : [];

const items = transformItems(
facetItems
.slice(0, this.getLimit())
Expand Down

0 comments on commit 5f9e138

Please sign in to comment.