How to update array state in react native?

react update state array element
react update object in array
push data into array react
react setstate array not working
react array of objects
react native array of objects
react hooks update array
react, ( usestate array push)

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

State

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

Setting the state

 setCurrentLocation() {
    var root = this;
    root.setState({
        markers: [
            ...root.state.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?

Thanks

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 });

updating one value in State array react native, You can't update the state like this. Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Now, you can add the item at the start of the array by using const list = [state.value, state.list]; instead. React State: Update item in array. In this part of the walkthrough, we will go through two cases to update items in an array: How to update the entire array in React state? How to update a specific item in array in React state?

Try this using create function

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

How to manage React State with Arrays, For each I want to show you a array example in React state, such as how to push an item to an array or how to update an item in an array, when� One solution is to use the react-addons-update package. Install it. npm i react-addons-update 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: import update from 'react-addons-update';

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: [],
        totalAmount:Number=0
    }


 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})
            })

Best way to update an array of state? React, Should I be pushing the new data to the array? So far, I'm using this code to get the data (it works) constructor(props) { super(props); this� For added new element into the array, push () should be the answer. For remove element and update state of array, below code works for me. splice (index, 1) can not work.

React/ReactJS: Update an Array State, ReactJS + CouchDB � Datepicker � Chat w/ Node.js & WebSocket � Rich Text Editor � React w/ Redux Example � Redux Reducer Array Update. const newArray = this.state.array.concat([newTask]) //wrap the newTask with [] so it is an array now this.setState({array: newArray}) And this works perfectly fine.

How to Add to an Array in React State using Hooks, push() does modify the array found in the variable searches , that modification never “hooks” over to React to update on the re-render. React� 1 to update state constructed like this you will have to find index of element you want to update, copy the array and change found index. it's easier and more readable if you keep list of records as object, with id as a key and record as a value.

Updating a value in a nested array of objects, “Red and Blue Pelikan Br 40 Eraser on White Surface” by Pixabay. Say we have a component with an array of to-do's, just like this: state = { If you want to update your array, you'll want to do something like this. var newStateArray = this.state.myArray.slice(); newStateArray.push('new value'); this.setState(myArray: newStateArray); Working on the state object directly is not desirable.

Comments
  • This question helped me to define array on the state. Thank you @John
  • This is not a good method @MayankShukla, this should be always done based on keys.
  • i tried this but I'm having undefined is not an object (evaluating 'cd[i].val = text') how to solve this? here's my question stackoverflow.com/questions/43197537/… thank you
  • @mori which way u tried, can you show your code, will help you :)
  • @MayankShukla i tried this 'markers[index].key = /*new value*/ 'abc';' thank you!
  • what is the name of key, here i just referenced key as any key of the object that u want to update. can you show ur array ?