Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting property from state object with key interpolation and destructuring

When i try to delete a property from state object based on value of foo variable

...
const [state, setState] = useState(initialState);
...
const {[foo], ...newState} = state;
setState({newState});

I got this SyntaxError

Parsing error: Unexpected token , // the one after [foo]
like image 789
Hayi Avatar asked Mar 15 '19 13:03

Hayi


2 Answers

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>
like image 110
Tholle Avatar answered Sep 25 '22 15:09

Tholle


A bit late to the party but if anyone wasn't satisfied with an answer here's my two cents.

setData((prevData) => {
  const newData = {...prevData}
  delete newData["key_here"]
  return newData;
})
like image 37
Aleksander Koko Avatar answered Sep 22 '22 15:09

Aleksander Koko