I am trying to save the search history in a react / redux app (using redux-actions) I am making in the reducer. I want to save the latest ten searches and have the latest at the beginning. I have an array of objects and I want to (immutably) add a new object at the beginning of the array and shift all the remaining results down one. I also don't want the array to grow larger than 10 elements. I am currently just overriding the initial element every time with this:
[setWorkPermit]: (state, action) => ({
...state,
searchHistory: Object.assign([...state.searchHistory], { [0]: action.payload }),
}),
I was hoping there was a clean way to do this in ES6. Any takers?
I think array slices could do the trick here!
Just build a new array containing the new object at index zero, and then a slice of the previous 0-9 indices like this:
searchHistory: [action.payload, ...state.searchHistory.slice(0,9)],
Hopefully this helps!