import { Facet } from '@akinon/next/types'; import { Middleware, UnknownAction } from '@reduxjs/toolkit'; import { setSelectedFacets } from '@theme/redux/reducers/category'; const getSelectedFacets = (facets: Array) => { return facets ?.map((facet) => { return { ...facet, data: { ...facet.data, choices: facet.data.choices.filter((choice) => choice.is_selected) } }; }) .filter((facet) => { return facet.data.choices.filter((choice) => choice.is_selected).length; }); }; const categoryMiddleware: Middleware = ({ dispatch, getState }) => { return (next) => (action) => { const result = next(action); const act = action as UnknownAction; if (act.type === 'category/setFacets') { const facets: Array = (result as { payload: Array }).payload; const selectedFacets = getSelectedFacets(facets); dispatch(setSelectedFacets(selectedFacets)); } else if (act.type === 'category/toggleFacet') { const selectedFacets = getSelectedFacets( getState().category.selectedFacets ); dispatch(setSelectedFacets(selectedFacets)); } return result; }; }; export default categoryMiddleware;