The correct way to remove a key from a reaction state

I use reaction state (v0.14) to hold pairs of key values โ€‹โ€‹of unsaved user identifiers and user objects. For instance:

onChange = (user, field) => { return (event) => { let newUser = _.clone(this.state[user.uuid] || user); _.assign(newUser, {[field]: event.target.value}); this.setState({ [user.uuid]: newUser }); } } render() { let usersJsx = users.map((user, i) => { return <div key={i}> <input type="text" value={user.name} onChange={this.onChange(user, 'name')}/> </div>; }); let numberUnsavedUsers = _.keys(this.state).length; // ... etc } 

All this works fine until I come to a save method:

 persistUsers = (event) => { let unsavedUsers = _.toArray(this.state); updateUsers(unsavedUsers, { onSuccessCb: (savedUsers) => { // Would prefer to remove these two lines and replace // with `this.setState({});` but this doesn't work... ie // the state is left untouched rather than being // replaced with `{}`. This makes sense. I guess I was hoping // someone might point me towards a this.replaceState() // alternative. this.setState({nothing: true}); // triggers a state change event. this.state = {}; // wipes out the state. } }); } 

I searched, but found that people modify nested objects or arrays, not top-level values.

+5
source share
1 answer

You need to use replaceState instead of setState

Update: replaceState is deprecated . You should follow the recommendations and use setState with null values.

Recommendation:

You must name the data and use setState so that you can work with it more easily.

instead:

 //bad this.setState({ [user.uuid]: newUser }); 

using:

 //good this.setState({ newUser: {uuid: user.uuid} }) 

If your state was {unsavedUsers: {userData}} instead of {userData} , you could easily setState({unsavedUsers: {}}) without entering replaceState .

replaceState is an anti-template because it is rarely used.

Original answer:

Like setState() , but deletes all existing status keys that are not in the newState object.

Documentation

this.replaceState({}) will delete all objects.

+5
source

All Articles