Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete key from state (Redux Reducer)

I have a state in Redux that currently renders like this:

Before click:

{0: {
    open: false,
    negation: false,
    close: false
    },
1: {
    open: false,
    negation: false,
    close: false,
    bool: "and"
    }
}

After click:

{0: {
    open: false,
    negation: false,
    close: false
    },
1: {}
}

I'd like to completely remove the key 1 (in general it's [action.id]).

Currently the cases in the reducer are:

case 'HANDLE_INCREASE_CHANGE':
  return {
    ...state,
    index: state.index + 1,
    [state.index + 1]: {
      open:false,
      negation: false,
      close: false,
      bool: 'and'
    }
  }
case 'HANDLE_DECREASE_CHANGE':
  return {
    ...state,
    index: state.index - 1,
    [state.index]: {}
  }

The wrong part is:

[state.index]: {}

Can you help me please? thanks a lot!

like image 705
SkuPak Avatar asked Oct 18 '25 20:10

SkuPak


2 Answers

You should just be able to call delete state[action.id]. Although as you're in a reducer function, you should take a copy of the state first, delete from that, then return the copied version.

case: 'HANDLE_DECREASE_CHANGE':
  const next = {...state}
  delete next[action.id]
  return next
like image 174
Matt Sugden Avatar answered Oct 20 '25 10:10

Matt Sugden


You are setting new properties to state object, to remove then you need to use delete. Remember to make a copy of the current sate first.

case: 'HANDLE_DECREASE_CHANGE':
  let nextState = {...state}
  delete nextState[propToDelete]
  return nextState

I believe it would be best to have an array of elements and not set properties directly to the sate object.

const iniitalState = {
 index: 0,
 elements: []
}

case 'HANDLE_INCREASE_CHANGE': {
  state.elements.push({
    open:false,
    negation: false,
    close: false,
    bool: 'and'
  })
  return {...state, index: state.index + 1, elements: [...state.elements] }
}
case 'HANDLE_DECREASE_CHANGE': {
  let newElements = [...state.elements]
  newElements.splice(action.indexToRemove, 1) // Removes Element

  return {...state, index: state.index - 1, elements: [...newElements] }
}
like image 43
Lucas Fabre Avatar answered Oct 20 '25 11:10

Lucas Fabre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!