So here is my state:
this.state = { ids: ['A', 'E', 'C'] };
How would I go about modifying the state so that 'E' at index 1 is changed to 'B'? Like for example:
this.setState({ ids[1]: 'B' });
How would this be done?
To update an object in a state array, call the map() method to iterate over the array and update the object that matches the condition. Copied! const updateObjectInArray = () => { setEmployees(current => current.
Syntax of setState To make the state change, React gives us a setState function that allows us to update the value of the state. Calling setState automatically re-renders the entire component and all its child components.
If we want to use arrays or objects in our React state, we have to create a copy of the value before modifying it. This is a cheat sheet on how to do add, remove, and update items in an array or object within the context of managing React state. The spread operator is syntactic sugar for creating a new copy of a reference.
It took me an hour of searching to find a straight to the point simple explanation of how to do this. Copy the array and edit the copy and then setState from the copy. Simple. Thanks for this! let ids = [...this.state.ids]; // create the copy of state array ids [index] = 'k'; //new value this.setState ( { ids }); //update the value
We need a different approach for this. One solution is to use the react-addons-update package. Install it. Then import it into your component. Now replacing the first element (index 0) of the state array variable countries with some different value can be achieved this way:
This is a cheat sheet on how to do add, remove, and update items in an array or object within the context of managing React state. The spread operator is syntactic sugar for creating a new copy of a reference. const handleRemove = (todo) => { const newTodos = todos.filter( (t) => t !== todo); setTodos(newTodos); }
My suggestion is to get used to use immutable operations, so you don't modify internal state object.
As pointed in the react docs:
Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.
In this case, you can [1] use slice()
to get a new copy of the Array, [2] manipulate the copy, and, then, [3] setState with the new Array. It's a good practice.
Something like that:
const newIds = this.state.ids.slice() //copy the array newIds[1] = 'B' //execute the manipulations this.setState({ids: newIds}) //set the new state
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With