Ankit Jayaprakash
Ankit Jayaprakash

Reputation: 1110

How do i clear array in redux state for a multi select

Thanks in advance. I need to clear my redux state array if the user clicks on the clear button. When they hit on each image the item is added to redux state array and the selected item get a border in UI. I have a Clear button which clears the user selection. How do i perform this?

My Actions and Reducers are here below:

Action

export const selectedItem = (selectedItem ) => {
    return {
        type: 'selected_Item',
        payload:selectedItem 
    }
}

Reducers

import _, { map, isEmpty } from 'lodash'

const INITIAL_STATE = {
    itemList: []
}

export default (state = INITIAL_STATE, action) => { 
    console.log('REDUX__ '+action.payload)
    switch (action.type) {
        case 'selected_Item':

        var idx = _.findIndex(state.itemList, function(o) { return o.ITEMID== action.payload.ITEMID; }); 
        if(idx!==-1){
            state.itemList.splice(idx, 1) 
            return { ...state, itemList: [...state.itemList] }
        }       
            return { ...state, itemList: [...state.itemList, action.payload] }


        default:
            return state;
    }
}

Do i have to maintain a separate reducer and action to clear this state array? How can i accomplish this. I prefer to have code support as am new to react native and redux.

Once again thanks for checking up.

Upvotes: 0

Views: 816

Answers (2)

Pavlo Kozlov
Pavlo Kozlov

Reputation: 1101

Try the code below.

Actions:

export const selectedItem = (selectedItem) => {
    return {
        type: 'selected_Item',
        payload:selectedItem 
    }
}

export const clearItems = () => {
    return {
        type: 'clear_Items'
    }
}

Reducers:

import _, { map, isEmpty } from 'lodash'

const INITIAL_STATE = {
    itemList: []
}

export default (state = INITIAL_STATE, action) => { 
    console.log('REDUX__ '+action.payload)
    switch (action.type) {
        case 'selected_Item':
          var idx = _.findIndex(state.itemList, function(o) { return o.ITEMID== action.payload.ITEMID; }); 
          if(idx!==-1){
              state.itemList.splice(idx, 1) 
              return { ...state, itemList: [...state.itemList] }
          }       
              return { ...state, itemList: [...state.itemList, action.payload] }
        case 'clear_Items':
          return {
            ...state,
            itemList: []
          }
        default:
            return state;
    }
}

Upvotes: 0

n1stre
n1stre

Reputation: 6086

Just add a case for a deletion:

case 'delete_items':
  return { ...state, itemList: [] }

Or even like this, if possible:

case 'delete_items':
  return { ...INITIAL_STATE }

Upvotes: 2

Related Questions