Deleting property from state object with key interpolation and destructuring
You cannot destructure dynamic keys like that, and updating state with a missing key will leave that key untouched, so it will not be removed from state.
You can set a state variable to undefined
to remove it from state.
Example
class App extends React.Component {
state = {
foo: "Foo",
bar: "Bar"
};
deleteStateVariable = param => {
this.setState(prevState => {
const state = { ...prevState };
state[param] = undefined;
return state;
});
};
render() {
return (
<div>
<div>{JSON.stringify(this.state)}</div>
<button onClick={() => this.deleteStateVariable("foo")}>
Delete Foo
</button>
<button onClick={() => this.deleteStateVariable("bar")}>
Delete Bar
</button>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
If you are using hooks the argument you pass to setState
will replace the current state entirely, so then you can destructure out the key you don't want.
Example
const { useState } = React;
function App() {
const [state, setState] = useState({
foo: "Foo",
bar: "Bar"
});
function deleteStateVariable(param) {
const { [param]: tmp, ...rest } = state;
setState(rest);
}
return (
<div>
<div>{JSON.stringify(state)}</div>
<button onClick={() => deleteStateVariable("foo")}>Delete Foo</button>
<button onClick={() => deleteStateVariable("bar")}>Delete Bar</button>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>
I think you can write the dynamic destructuring like this:
let tmpVal = ""
const {[foo]: tmpVal, ...state} = this.state;
this.setState({state});
But it won't delete the property from the state.