score:53
while updating state the key part is to treat it as if it is immutable. any solution would work fine if you can guarantee it.
here is my solution using immutability-helper:
var update = require('immutability-helper');
handlecommentedit: function(id, text) {
var data = this.state.data;
var commentindex = data.findindex(function(c) {
return c.id == id;
});
var updatedcomment = update(data[commentindex], {text: {$set: text}});
var newdata = update(data, {
$splice: [[commentindex, 1, updatedcomment]]
});
this.setstate({data: newdata});
},
following questions about state arrays may also help:
score:14
you can do this with multiple way, i am going to show you that i mostly used. when i am working with arrays in react usually i pass a custom attribute with current index value, in the example below i have passed data-index attribute, data- is html 5 convention.
ex:
//handlechange method.
handlechange(e){
const {name, value} = e,
index = e.target.getattribute('data-index'), //custom attribute value
updatedobj = object.assign({}, this.state.arr[i],{[name]: value});
//update state value.
this.setstate({
arr: [
...this.state.arr.slice(0, index),
updatedobj,
...this.state.arr.slice(index + 1)
]
})
}
score:24
trying to clean up/ explain better how to do this and what's going on.
- first, find the index of the element you're replacing in the state array.
- second,
update
the element at that index - third, call
setstate
with the new collection
import update from 'immutability-helper';
// this.state = { employees: [{id: 1, name: 'obama'}, {id: 2, name: 'trump'}] }
updateemployee(employee) {
const index = this.state.employees.findindex((emp) => emp.id === employee.id);
const updatedemployees = update(this.state.employees, {$splice: [[index, 1, employee]]}); // array.splice(start, deletecount, item1)
this.setstate({employees: updatedemployees});
}
edit: there's a much better way to do this w/o a 3rd party library
const index = this.state.employees.findindex(emp => emp.id === employee.id);
employees = [...this.state.employees]; // important to create a copy, otherwise you'll modify state outside of setstate call
employees[index] = employee;
this.setstate({employees});
score:145
i quite like doing this with object.assign rather than the immutability helpers.
handlecommentedit: function(id, text) {
this.setstate({
data: this.state.data.map(el => (el.id === id ? object.assign({}, el, { text }) : el))
});
}
i just think this is much more succinct than splice and doesn't require knowing an index or explicitly handling the not found case.
if you are feeling all es2018, you can also do this with spread instead of object.assign
this.setstate({
data: this.state.data.map(el => (el.id === id ? {...el, text} : el))
});
Source: stackoverflow.com
Related Query
- Whats the best way to update an object in an array in ReactJS?
- What is the best way to update object array value in React
- ReactJS : What is the best way to give keys in array element
- ReactJS best way to update the state with asynchronous setState
- How to use setState to update the property of an object inside an array the right way in class component?
- Best way to group an array with property of object and how to render the result
- Whats the best way to add an SVG to ReactJS
- ReactJS How to update the state in object which is in the array
- Is there a way to send a object instead of array to the Back-End ? - ReactJS
- What is the best way to add a value to an array in state
- Whats the best way to conditionally add readOnly in React?
- Is there any way to update a specific index from the array in Firestore
- In React, what is the right way to update nested array state items
- If a function updates a state variable which is an object and is called from a child component, what's the best way to avoid infinite renders?
- What is the best way to update my react state when data in database changes?
- update the array of object using useState hook
- Is there a way to skip the yup validation to the last object in an array of objects?
- ReactJS useState hook: Can I update array of objects using the state variable itself?
- Update a redux array of object but not re-render the component
- Best way to use Mongoose to update an Array of Objects?
- How to display the content of an array inside an object in Reactjs
- how to update nested array values in immutable way in reactjs
- Cleaner way to update object in array
- Update nested object in array in ReactJs
- how do i update state in react for updating the value of an object inside an array using array.map function
- What is the best to update state inside an array
- What is the best way of calculating the total amount (quantity*price) from the array of objects (State) in react?
- Best way to set state of object using dynamic key name? - reactjs
- What is the best way convert object keys from snake case to camel case and vice versa?
- Use SetState to update one of the item in array object in react
More Query from same tag
- React: using ? and : to make a decision
- How do you remove a class from elements inside a component in React.JS when clicking outside given component?
- how to redirect to home page after submitting redux-form?
- Integrates react-route Links into Material UI list
- how to add onchange event in react js application
- Invalid hook call in React in useEffect
- How to customize arrows styling to react-responsive carousel
- react forms Controlled component
- how to write a onchange event for a returned component
- React fetch API won't show any data
- React Redux - Can't pass the string via dispatch action
- React setter function not updating state as expected
- Always stumble on this error Cannot read property 'map' of undefined
- in reactjs componentWillMount(), how to get which component?
- React useState with className and styled components hover out
- SetState outside body reactjs
- React global component
- 'react-dnd' does not contain an export named 'DragDropContext'
- Using nested rendering in React
- history.push not working in wait or sync until button click
- Highlight textbox on edit
- componentDidMount not changing state for array variable but it works if changed to int instead of array
- Why does the code(funtional) for the hook keep rendering? (compared to Class)
- can't render in else statement
- Gatsby site isn't rendering gifs
- How to inherit from a css file in react
- npx create-react-app prompting to globally uninstall non-existent create-react-app package?
- What type declaration to use for a generic T that may or may not be hierarchical?
- How to concatenate string with JSON in react.js
- SetTimeout mutates my state despite I am using prevState