I am trying to update only one element in an array state but i am not sure of how to do it.


constructor(props) {
    this.state = {
        markers: [],

Setting the state

 setCurrentLocation() {
    var root = this;
        markers: [
                coordinate: {
                    latitude: parseFloat(root.state.currentLat),
                    longitude: parseFloat(root.state.currentLon)
                key: root.state.currentLat,
                image: pinCurrentLocation


If i want to change the key in the fourth element of marker, how do i do that?


Solution 1

Important point is, we should not mutate the state array directly, always do the changes in new array and then use setState to update the state value.

As suggested by Doc:

Never mutate this.state directly, Treat this.state as if it were immutable.

Basic flow of updating a state array is:

1- First create the copy of state array.

2- Find index of the item (if index is available skip this one).

3- Update the value of item at that index.

4- Use setState to update the state value.

Multiple solutions are possible:

1- Use array.map and check which element you want to update, when you find that element return a new object for that with updated key value otherwise just return the same object. Like this:

let newMarkers = markers.map(el => (
      el.name==='name'? {...el, key: value}: el
this.setState({ markers });

2- We can also use array.findIndex to find the index of that particular item, then update the values of that item. Like this:

let markers = [...this.state.markers];
let index = markers.findIndex(el => el.name === 'name');
markers[index] = {...markers[index], key: value};
this.setState({ markers });

Loop will be not required if we know the index of the item, directly we can write:

let markers = [ ...this.state.markers ];
markers[index] = {...markers[index], key: value};
this.setState({ markers });

Solution 2

Try this using create function

onEditComparatorClicked(i) {
   let editableComparatorIndexes = [...this.state.markers];
   editableComparatorIndexes[i] = 1;

Solution 3


this.state = {

update array

var barcode_text='hi';
 this.setState({ barcodeArray:[...this.state.barcodeArray,barcode_text] })}

Solution 4

I am trying to push value in an array state and set value like this and define state array and push value by map function.

 this.state = {
        createJob: [],

 your_API_JSON_Array.map((_) => {
                this.setState({totalAmount:this.state.totalAmount += _.your_API_JSON.price})
                this.state.createJob.push({ id: _._id, price: _.your_API_JSON.price })
                return this.setState({createJob: this.state.createJob})