reactjs - How to add one item to the top of a redux store list while removing the bottom item from the list -
i remove 1 item redux store list, once has reached number , return new store new value added, minus first value on list (array.shift).
think of twitter stream fills store every 6 tweets removing 1 bottom of list , adding new 1 top.
code:
// ------------------------------------ // action handlers // ------------------------------------ const action_handlers = { [init_data]: (state, action) => { if (state.length < 5) { return [ ...state, action.payload.stream ] } else { return [ ...state.shift(), action.payload.stream ] } }, [disconnect]: (state, action) => ({ ...state, ...action.payload }) } // ------------------------------------ // reducer // ------------------------------------ const initialstate = [] export default function twitterstreamreducer (state = initialstate, action) { const handler = action_handlers[action.type] return handler ? handler(state, action) : state }
the above code returns new store when lentgh > 5 , deletes old tweets not bottom one.
any ideas on best way without mutating state?
you can use array.slice returns shallow copy of original array minus sliced items. not use shift() mutates state , can cause sorts of issues.
return [...state.slice(1), action.payload.stream]
Comments
Post a Comment