Reputation: 367
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!
Upvotes: 4
Views: 8340
Reputation: 874
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
Upvotes: 8
Reputation: 1951
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] }
}
Upvotes: 2
Reputation: 1170
delete the key you want removed:
const resultingState = {...state, index: state.index - 1}
delete resultingState[state.index]
return resultingState
or extract it away with rest parameters:
const {...extractedState, [state.index]: ignored} = state
return {...extractedState, index: state.index - 1}
Upvotes: 1