Answer the question
In order to leave comments, you need to log in
How to reset sorting in redux? Or how to return the previous state of an array if it is already sorted in Redux?
There are three states for sorting goods: by price descending, by price ascending and by default (sorting is reset)
So, initially the page with goods is loaded without sorting and the action 'FETCH_GOODS_SUCCESS'
fires '). Sorting in ascending and descending order works well. But when, after this sorting, we select "Default sorting" (i.e., we reset the sorting), the goods can no longer return to their original state. the `goods` array has already been sorted.
This is where the problem lies. How to return the previous state of the goods array, as it was before sorting? Is there a way to save the original state?
const initialState = {
goods: [],
loading: true,
sortOrder: 'default',
};
const reducer = (state = initialState, action) => {
switch(action.type) {
case 'FETCH_GOODS_SUCCESS':
// подгрузка товаров без сортировки
return {
...state,
goods: action.payload,
loading: false
};
case 'SORT_GOODS':
// выполняем сортировку в зависимости от того что выбрали в селекте
// action.payload.type может быть равным 'increase' || 'decrease' || 'default' (default - обнуляем сортировку)
switch(action.payload.type) {
case 'increase':
const goodsListInc = state.goods.sort((prev, next) => prev.price - next.price);
return {
...state,
goods: goodsListInc,
sortOrder: 'increase'
};
case 'decrease':
const goodsListDec = state.goods.sort((prev, next) => next.price - prev.price);
return {
...state,
goods: goodsListDec,
sortOrder: 'decrease'
};
default: // обнуляем сортировку
return {
...state,
goods: // Не знаю что написать тут. Ведь в этот момент массив goods уже отстортирован,
sortOrder: 'default'
};
}
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question