Skip to content

Commit 569d573

Browse files
samoussHaroenv
authored andcommitted
fix(sortBy): ensure a return value for getWidgetSearchParameters (#4126)
This PR ensures that the `sortBy` widget always return a value for `index` (or at least don't remove the current one). The call to `getWidgetSearchParameters` might happen once before the `init` step. The current implementation relies on the `init` step (`this.initialIndex`) when no value is found in the `uiState`. When the widget is not initialized the value set is `undefined` which means that it removes the current index. To avoid this problem we fall back on the current index when none of the conditions are met. It's the responsibility of the widget to set a value. It doesn't make sense to return `SearchParameters` without an index.
1 parent 952dc70 commit 569d573

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-2
lines changed

src/connectors/sort-by/__tests__/connectSortBy-test.js

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -530,7 +530,7 @@ See documentation: https://www.algolia.com/doc/api-reference/widgets/sort-by/js/
530530
);
531531
});
532532

533-
test('should enforce the default value on empty UiState', () => {
533+
test('should return the initial index on empty UiState with widget initialized', () => {
534534
const [widget, helper, refine] = getInitializedWidget();
535535

536536
refine('other');
@@ -549,6 +549,32 @@ See documentation: https://www.algolia.com/doc/api-reference/widgets/sort-by/js/
549549
})
550550
);
551551
});
552+
553+
test('should return the current index on empty UiState without widget initialized', () => {
554+
const sortBy = connectSortBy(() => {});
555+
const widget = sortBy({
556+
items: [
557+
{ label: 'Sort products by relevance', value: 'relevance' },
558+
{ label: 'Sort products by price', value: 'priceASC' },
559+
{ label: 'Sort products by magic', value: 'other' },
560+
],
561+
});
562+
563+
const actual = widget.getWidgetSearchParameters(
564+
new SearchParameters({
565+
index: 'relevance',
566+
}),
567+
{
568+
uiState: {},
569+
}
570+
);
571+
572+
expect(actual).toEqual(
573+
new SearchParameters({
574+
index: 'relevance',
575+
})
576+
);
577+
});
552578
});
553579
});
554580
});

src/connectors/sort-by/connectSortBy.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,7 @@ export default function connectSortBy(renderFn, unmountFn = noop) {
170170
getWidgetSearchParameters(searchParameters, { uiState }) {
171171
return searchParameters.setQueryParameter(
172172
'index',
173-
uiState.sortBy || this.initialIndex
173+
uiState.sortBy || this.initialIndex || searchParameters.index
174174
);
175175
},
176176
};

0 commit comments

Comments
 (0)