Tom Söderlund
Tom Söderlund

Reputation: 4747

Can’t remove items from a React state collection

I have these two methods defined in my React component:

handleAddMetric() {
    const metricKey = prompt('Name/key of metric');
    const newMetricItem = {
        name: metricKey,
        value: 100
    }
    let newMetrics = {};
    newMetrics[metricKey] = newMetricItem;
    const updatedMetrics = Object.assign({}, this.state.metrics, newMetrics);
    this.setState({ metrics: updatedMetrics });
}

handleRemoveMetric(keyName) {
    let updatedMetrics = this.state.metrics;
    delete updatedMetrics[keyName];
    console.log('handleRemoveMetric', this, keyName, updatedMetrics);
    this.setState({ metrics: updatedMetrics });
}

Adding new values to this.state.metrics works fine, but deleting:

<button onClick={this.handleRemoveMetric.bind(this, key)}>Delete</button>

...calls my handleRemoveMetric function but doesn’t update the collection.

I first it was some issue with this but that doesn’t seem to be the case.

Any ideas?

Update: The console output is:

handleRemoveMetric Metrics {props: Object, context: Object, refs: Object, updater: Object, state: Object…}componentWillUnmount: function ()context: Objectprops: Objectref: Objectrefs: ObjectsetState: function (data, cb)state: Objectupdater: Object_reactInternalInstance: ReactCompositeComponentWrapperisMounted: (...)replaceState: (...)__proto__: ReactComponent
"myMetricKey"
Object {MRR: Object, moneyInBank: Object, wow: Object}

...so at least the collection is updated locally.

Upvotes: 0

Views: 79

Answers (1)

vijayst
vijayst

Reputation: 21846

You need to copy it over to a new object.

const metrics = { 
  ...this.state.metrics, 
  [keyName]: null 
}; 
this.setState({ metrics }); 

should work.

Upvotes: 1

Related Questions