Update state of array nested inside object (ReactJS) - javascript

I have an object in state ("car") with multiple keys, one of which is an array ("features"). There's a couple things I'm trying to do with it.
I want to push another string (another feature) onto the "features" array every time I click the "Add Feature" button.
I want to be able to update the state of each string/feature in the "features" array when I type in the respective input.
I've researched this online quite a bit and haven't found anything (maybe because this isn't possible). Either way, here's my code:
class Car extends React.Component {
state = {
car: {make: 'Toyota', model: 'Camry', features: []},
}
handleChange = (e, index) => {
const value = e.target.value
let features = this.state.car.features.slice() // create mutable copy of array
features = features[index].concat(value)
this.setState({...this.state.car, features: features})
}
handleAddFeature = () => {
let features = this.state.car.features.slice()
features.push('')
this.setState({...this.state.car, features: features})
}
render() {
return (
{
this.state.car.features.map((f, index) => { return <input key={index} onChange={e => this.handleChange(e, index)}>{feature}</input>
}
<button onClick={this.handleAddFeature}>Add Feature</button>
)
}
}

Okay, I got this working in a very similar way to #Snkendall's answer. My handleChange function is listed below:
handleChange = (e, index,) => {
let array = this.state.car.features.slice() // create mutable copy of the array
array[index] = e.target.value // set the value of the feature at the index in question to e.target.value
const newObj = { ...this.state.car, features: array } // create a new object by spreading in the this.state.car and overriding features with our new array
this.setState({ car: newObj }) // set this.state.car to our new object
}
The difference between this solution and #Snkendall's is the defining of a newObj variable. That turns out to the be the only way to update an individual key nested inside a state object.

There are a few things that could be causing you problems... if your component has a state, you should use a constructor, and bind your 'this' references inside it to prevent 'this' from referencing the global. You just wrap your state like this:
class Car extends React.Component {
constructor() {
super()
this.state = {
car: {make: 'Toyota', model: 'Camry', features: []},
}
this.handleChange = this.handleChange.bind(this)
this.handleAddFeature = this.handleAddFeature.bind(this)
}
This is a really great article for thinking about 'this': http://2ality.com/2017/12/alternate-this.html
Another area that might cause you problems is features = features[index].concat(value)... because you're concatting the input tag's value onto the current string on state over and over again with every change (keystroke). You can just reset the value of the element at that index in the array like this:
handleChange = (e, index) => {
const value = e.target.value
let features = this.state.car.features.slice()
features[index] = value
this.setState({...this.state.car, features})
}
and that way, each keystroke just resets the value on state to reflect the change created in the input. You actually wouldn't need to use the handleAddFeature at all, since the state is already updated with handleChange.
I'm changing features:features to just features because ES6 destructuring has this fun thing where if a key and it's value is the same, you only need to reference it once, and it figures it out. It's just a cool way to keep your code even DRYer.

Ad.1
handleAddFeature = () => {
const car = this.state.car
car.features.push('Your feature')
this.setState({ car })
}
Just create copy and push to car features new value.
Ad. 2
Create component called e.g. Feature. He will have own state where you modify string and through props you can extract data to your "car".

Related

How do I change a value in an instance of a Typescript class?

I have a Fruit class:
export class Fruit {
constructor(public id: number, public name: string) {}
public changeName(_name: string): void {
console.log('changing name')
this.name = _name
}
}
And I implement it like so:
import React from 'react'
import { Fruit } from '../classes/fruit'
const HomePage = () => {
let fruit = new Fruit(1, 'apple')
return (
<div>
{fruit.name} <----- I am expecting this to update on the DOM when i click the button *********
<button onClick={() => fruit.changeName('banana')}>
change the name
</button>
</div>
)
}
export default HomePage
But when I click the button, the fruit name on the screen does not change. It stays as 'apple' . Does anyone know what I am doing wrong? I am new to Typescript
Some notes:
React functional components do not work like that. If your data changes over time, you need to define some state, with a hook: const [fruit, setFruit] = React.useState(initialFruit).
That still won't work, as your fruit is a mutable object, React does not "see" in-place imperative updates. Not ideal, but you could fool React by using an object wrapper as the state value: { value: someFruit } (this works because in JS { value: 1 } !== { value: 1 }.
As you see, React's whole idea involves immutable values (AKA functional programming). Consider writing classes with immutable setters (public changeName(name: string): Fruit), and you'll be able to write nice declarative code like this: <button onClick={() => setFruit(fruit.changeName('banana'))}>.
export class Fruit {
constructor(public id: number, public name: string) {}
public changeName(name: string): Fruit {
return new Fruit(this.id, name)
}
}
So, here's the thing. This isn't going to work.
First of all, any variables created in a react functional component's render function only exist during that render. So when you do:
let fruit = new Fruit(1, 'apple')
Then every single time your component renders you create a new Fruit with an id of 1 a name of "apple". Any changes you make to that object after the render will never be seen, because to be seen the component would need to re-rerender, which makes a new Fruit from scratch.
The way you get around this is to use "state" which preserves values between component renders.
So instead, let's say you had this:
const HomePage = () => {
let [fruit, setFruit] = useState(new Fruit(1, 'apple'))
//...
}
But the problem is that state is expected to be immutable, which means if the state were to change it expects a new object entirely, and it's forbidden to change a piece of the state.
This is because react can't tell if anything actually change in state unless you replace the state entirely.
So to fix that you would need to set a brand new object when you change the state.
This should work:
const HomePage = () => {
let [fruit, setFruit] = useState(new Fruit(1, 'apple'))
return (
<div>
{fruit.name}
<button onClick={() => setFruit(new Fruit(fruit.id, 'banana')}>
change the name
</button>
</div>
)
}
But that's kid of annoying. This is why it's not recommended to put mutable instances in state. And that means there usually isn't much need for instances of a class at all, and it's usually far simpler to just store objects in state.
// declare state
let [fruit, setFruit] = useState({ id: 1, name: 'apple' })
// set state
setFruit({ ...fruit, name: 'banana' })

Changing a child components state changes the parent components props

Parent component is a header
Child component is a form which is used to change values appearing in the header after a save which fires a redux action.
I set the child state with
constructor(props) {
super(props);
this.state = {
object: { ...props.object },
hidden: props.hidden,
};
}
The form is used to render the state.object and modify the state.object.
When I modify state.object, the props from the parent component change as well.
handleObjectChange = (event, key, subkey) => {
console.log('props', this.props.object.params);
console.log('state', this.state.object.params);
event.preventDefault();
const value = this.handlePeriod(event.target.value);
this.setState((prevState) => {
const object = { ...prevState.object };
object[key][subkey] = value;
return { object };
});
}
Console output:
newvalueijusttyped
newvalueijusttyped
This behavior actually goes all the way up to modifying the redux store without ever having dispatched an action.
Would appreciate a solution for this issue
Update:
Changing the constructor to this solved the issue
constructor(props) {
super(props);
this.state = {
object: JSON.parse(JSON.stringify(props.object)),
hidden: props.hidden,
};
}
Why doesn't the object spread operator achieve what I'm trying to accomplish?
Javascript object are assigned by reference so when you do
constructor(props) {
super(props);
this.state = {
object: props.object,
hidden: props.hidden,
};
}
state is referencing the redux state object(if it is a redux state). So now when you use
this.setState((prevState) => {
const object = { ...prevState.object };
object[key][subkey] = value;
return { object };
});
Although you would assume that you have cloned the object value into a new object. However Spread syntax does only a one level copy of the object.
From the Spread Syntax MDN docs:
Note: Spread syntax effectively goes one level deep while copying an
array. Therefore, it may be unsuitable for copying multidimensional
arrays as the following example shows (it's the same with
Object.assign() and spread syntax).
var a = [1, [2], [3]]; var b = [...a]; b.shift().shift(); // 1 //
Now array a is affected as well: [[], [2], [3]]
So effectively
object[key][subkey] = value;
changes the value directly in redux store.
Solution is create a nested copy like
const object = { ...prevState.object,
[key]: {
...prevState[key],
[subkey]: { ...prevState[key][subkey]}
}
};
object[key][subkey] = value;
Objects in javascript are 'passed by reference'.
If you are passing the parent's props as state to the children, then when you change the state, you are in effect mutating the very same object that was passed to it.
Use Object.assign() to create a clone of the data before you make it part of the child's state.

Get user object properties from Firebase in React

I have a user db in Firebase that uses the unique user id as the Key and within that key/value pairs like name: 'jane doe', email: 'jane#doe.com', etc. What I want to do is map the object and get the key values within. I'm able to get the Key (user id), but not the object key value pairs. Here's my code:
export default class Home extends Component {
constructor(props) {
super(props);
var users = {};
this.state = { users };
}
componentDidMount() {
const dbRoot = firebaseDb.database().ref().child('users');
dbRoot.on('value', snap => {
const dbUsers = snap.val();
this.setState({
users: dbUsers
});
});
}
render() {
return (
<div>
<div>
{Object.keys(this.state.users).map(function(user, i) {
return <div key={i}>Key: {user}, Value: {user.name}</div>;
})}
</div>
</div>);
}
}
user.name comes back undefined. I've tried using this.state.users.name but I get a "state is undefined" message. Can someone point me in the right direction. Thanks!
You have two main problems with your code. The first is that you cannot access this.state inside the callback of your map() function because this is bound to that function and not to the whole class. There are a couple of ways to keep the this variable bound to the class but the cleanest way is to use the Arrow function syntax.
Once you do that, you will still have a problem. You are using Object.keys which will only map over the keys of your result, but you are treating it as if it will pass the whole user object to the function. In order to access the user object inside of your callback function, you will need to use the bracket notation with the key.
With those two things in mind, your code should look something like this:
{Object.keys(this.state.users).map(key => {
return <div key={key}>Key: {key}, Value: {this.state.users[key].name}</div>;
})}

Update Array in React

I am coming from Angular 1.x and looking to update an unordered list with React / Redux.
In console.log, I am seeing the array being updated, but it doesn't seem to bind to the DOM. I have the following --
onKeyPress of an input, I have a function that pushes to messages array.
<ul className="list-inline">
{messages.map(function(message, key){
return (
<li key={key} message={message}>{message}</li>
);
})}
</ul>
Update
I have the following (but no luck yet) Some notes. I am using Firebase to listen for events, and add to an array. Wondering if its a bind issue? --
class Comments extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {messages: this.props.messages};
}
componentDidMount() {
const path = '/comments/all';
// Firebase watches for new comments
firebase
.database()
.ref(path)
.on('child_added', (dataSnapshot) => {
this.state.messages.push(dataSnapshot.val());
this.setState({
messages: this.state.messages
});
//console.log(dataSnapshot.val());
});
}
render() {
const messages = this.state.messages;
return (
<ul className="list-inline">
{messages.map(function(message, key){
<li key={key}>{message}</li>
})}
</ul>
);
}
}
You need messages to be set in the components state.
getInitialState() {
return {
messages: []
}
}
Then in your function, set the state:
this.setState({messages: updatedMessages})
and then map over the messages state, or a messages variable in render:
const messages = this.state.messages;
<ul className="list-inline">
{messages.map(function(message, key){
etc...
put messages array and set state change to render DOM. You should read https://facebook.github.io/react/docs/component-specs.html
Two issues:
You mustn't directly mutate the state object in React (see: Do Not Directly Modify State). Instead, provide a new array via setState with the new entry in it.
When updating state based on existing state, you must use the function callback version of setState, not the version accepting an object, because state updates are asynchronous and may be merged (see: State Updates May Be Asynchronous, though it's really "will," not "may"). Using the object version often happens to work, but it isn't guaranteed to; indeed, it's guaranteed not to, at some point.
Let's look at various ways to update an array:
Adding to the end (appending):
this.setState(({messages}) => ({
messages: [...messages, newValue]
}));
In your case, newValue would be dataSnapshot.val().
(We need the () around the object initializer because otherwise the { would seem to start a full function body instead of a concise expression body.)
Adding to the beginning (prepending):
Largely the same, we just insert the new element in a different place:
this.setState(({messages}) => ({
messages: [newValue, ...messages]
}));
(We need the () around the object initializer because otherwise the { would seem to start a full function body instead of a concise expression body.)
Updating an existing item in the array
Suppose you have an array of objects and want to update one you have in the variable targetElement:
this.setState(({messages}) => {
messages = messages.map(element => {
return element === targetElement
? {...element, newValue: "new value"}
: element;
});
return {messages};
}));
Removing an existing item in the array
Suppose you have an array of objects with id values and want to remove the one with targetId:
this.setState(({messages}) => {
messages = messages.filter(element => element.id !== targetId);
return {messages};
}));
By Index
Warning: Updating arrays in React by index is generally not best practice, because state updates are batched together and indexes can be out of date. Instead, work based on an identifying property or similar.
But if you have to use an index and you know it won't be out of date:
this.setState(({messages}) => {
messages = messages.filter((e, index) => index !== targetindex);
return {messages};
}));

How can I update state.item[1] in state using setState?

I'm creating an app where the user can design his own form. E.g. specify name of the field and details of which other columns that should be included.
The component is available as a JSFiddle.
My initial state looks like this:
var DynamicForm = React.createClass({
getInitialState: function() {
var items = {};
items[1] = { name: 'field 1', populate_at: 'web_start',
same_as: 'customer_name',
autocomplete_from: 'customer_name', title: '' };
items[2] = { name: 'field 2', populate_at: 'web_end',
same_as: 'user_name',
autocomplete_from: 'user_name', title: '' };
return { items };
},
render: function() {
var _this = this;
return (
<div>
{ Object.keys(this.state.items).map(function (key) {
var item = _this.state.items[key];
return (
<div>
<PopulateAtCheckboxes this={this}
checked={item.populate_at} id={key}
populate_at={data.populate_at} />
</div>
);
}, this)}
<button onClick={this.newFieldEntry}>Create a new field</button>
<button onClick={this.saveAndContinue}>Save and Continue</button>
</div>
);
}
I want to update the state when the user changes any of the values, but I'm having a hard time to target the correct object:
var PopulateAtCheckboxes = React.createClass({
handleChange: function (e) {
item = this.state.items[1];
item.name = 'newName';
items[1] = item;
this.setState({items: items});
},
render: function() {
var populateAtCheckbox = this.props.populate_at.map(function(value) {
return (
<label for={value}>
<input type="radio" name={'populate_at'+this.props.id} value={value}
onChange={this.handleChange} checked={this.props.checked == value}
ref="populate-at"/>
{value}
</label>
);
}, this);
return (
<div className="populate-at-checkboxes">
{populateAtCheckbox}
</div>
);
}
});
How should I craft this.setState to get it to update items[1].name ?
Here's how you can do it without helper libs:
handleChange: function (e) {
// 1. Make a shallow copy of the items
let items = [...this.state.items];
// 2. Make a shallow copy of the item you want to mutate
let item = {...items[1]};
// 3. Replace the property you're intested in
item.name = 'newName';
// 4. Put it back into our array. N.B. we *are* mutating the array here,
// but that's why we made a copy first
items[1] = item;
// 5. Set the state to our new copy
this.setState({items});
},
You can combine steps 2 and 3 if you want:
let item = {
...items[1],
name: 'newName'
}
Or you can do the whole thing in one line:
this.setState(({items}) => ({
items: [
...items.slice(0,1),
{
...items[1],
name: 'newName',
},
...items.slice(2)
]
}));
Note: I made items an array. OP used an object. However, the concepts are the same.
You can see what's going on in your terminal/console:
❯ node
> items = [{name:'foo'},{name:'bar'},{name:'baz'}]
[ { name: 'foo' }, { name: 'bar' }, { name: 'baz' } ]
> clone = [...items]
[ { name: 'foo' }, { name: 'bar' }, { name: 'baz' } ]
> item1 = {...clone[1]}
{ name: 'bar' }
> item1.name = 'bacon'
'bacon'
> clone[1] = item1
{ name: 'bacon' }
> clone
[ { name: 'foo' }, { name: 'bacon' }, { name: 'baz' } ]
> items
[ { name: 'foo' }, { name: 'bar' }, { name: 'baz' } ] // good! we didn't mutate `items`
> items === clone
false // these are different objects
> items[0] === clone[0]
true // we don't need to clone items 0 and 2 because we're not mutating them (efficiency gains!)
> items[1] === clone[1]
false // this guy we copied
You could use the update immutability helper for this:
this.setState({
items: update(this.state.items, {1: {name: {$set: 'updated field name'}}})
})
Or if you don't care about being able to detect changes to this item in a shouldComponentUpdate() lifecycle method using ===, you could edit the state directly and force the component to re-render - this is effectively the same as #limelights' answer, as it's pulling an object out of state and editing it.
this.state.items[1].name = 'updated field name'
this.forceUpdate()
Post-edit addition:
Check out the Simple Component Communication lesson from react-training for an example of how to pass a callback function from a state-holding parent to a child component which needs to trigger a state change.
Wrong way!
handleChange = (e) => {
const { items } = this.state;
items[1].name = e.target.value;
// update state
this.setState({
items,
});
};
As pointed out by a lot of better developers in the comments: mutating the state is wrong!
Took me a while to figure this out. Above works but it takes away the power of React. For example componentDidUpdate will not see this as an update because it's modified directly.
So the right way would be:
handleChange = (e) => {
this.setState(prevState => ({
items: {
...prevState.items,
[prevState.items[1].name]: e.target.value,
},
}));
};
To modify deeply nested objects/variables in React's state, typically three methods are used: vanilla JavaScript's Object.assign, immutability-helper and cloneDeep from Lodash.
There are also plenty of other less popular third-party libs to achieve this, but in this answer, I'll cover just these three options. Also, some additional vanilla JavaScript methods exist, like array spreading, (see #mpen's answer for example), but they are not very intuitive, easy to use and capable to handle all state manipulation situations.
As was pointed innumerable times in top voted comments to the answers, whose authors propose a direct mutation of state: just don't do that. This is a ubiquitous React anti-pattern, which will inevitably lead to unwanted consequences. Learn the right way.
Let's compare three widely used methods.
Given this state object structure:
state = {
outer: {
inner: 'initial value'
}
}
You can use the following methods to update the inner-most inner field's value without affecting the rest of the state.
1. Vanilla JavaScript's Object.assign
const App = () => {
const [outer, setOuter] = React.useState({ inner: 'initial value' })
React.useEffect(() => {
console.log('Before the shallow copying:', outer.inner) // initial value
const newOuter = Object.assign({}, outer, { inner: 'updated value' })
console.log('After the shallow copy is taken, the value in the state is still:', outer.inner) // initial value
setOuter(newOuter)
}, [])
console.log('In render:', outer.inner)
return (
<section>Inner property: <i>{outer.inner}</i></section>
)
}
ReactDOM.render(
<App />,
document.getElementById('react')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.10.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.10.2/umd/react-dom.production.min.js"></script>
<main id="react"></main>
Keep in mind, that Object.assign will not perform a deep cloning, since it only copies property values, and that's why what it does is called a shallow copying (see comments).
For this to work, we should only manipulate the properties of primitive types (outer.inner), that is strings, numbers, booleans.
In this example, we're creating a new constant (const newOuter...), using Object.assign, which creates an empty object ({}), copies outer object ({ inner: 'initial value' }) into it and then copies a different object { inner: 'updated value' } over it.
This way, in the end the newly created newOuter constant will hold a value of { inner: 'updated value' } since the inner property got overridden. This newOuter is a brand new object, which is not linked to the object in state, so it can be mutated as needed and the state will stay the same and not changed until the command to update it is ran.
The last part is to use setOuter() setter to replace the original outer in the state with a newly created newOuter object (only the value will change, the property name outer will not).
Now imagine we have a more deep state like state = { outer: { inner: { innerMost: 'initial value' } } }. We could try to create the newOuter object and populate it with the outer contents from the state, but Object.assign will not be able to copy innerMost's value to this newly created newOuter object since innerMost is nested too deeply.
You could still copy inner, like in the example above, but since it's now an object and not a primitive, the reference from newOuter.inner will be copied to the outer.inner instead, which means that we will end up with local newOuter object directly tied to the object in the state.
That means that in this case mutations of the locally created newOuter.inner will directly affect the outer.inner object (in state), since they are in fact became the same thing (in computer's memory).
Object.assign therefore will only work if you have a relatively simple one level deep state structure with innermost members holding values of the primitive type.
If you have deeper objects (2nd level or more), which you should update, don't use Object.assign. You risk mutating state directly.
2. Lodash's cloneDeep
const App = () => {
const [outer, setOuter] = React.useState({ inner: 'initial value' })
React.useEffect(() => {
console.log('Before the deep cloning:', outer.inner) // initial value
const newOuter = _.cloneDeep(outer) // cloneDeep() is coming from the Lodash lib
newOuter.inner = 'updated value'
console.log('After the deeply cloned object is modified, the value in the state is still:', outer.inner) // initial value
setOuter(newOuter)
}, [])
console.log('In render:', outer.inner)
return (
<section>Inner property: <i>{outer.inner}</i></section>
)
}
ReactDOM.render(
<App />,
document.getElementById('react')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.10.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.10.2/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
<main id="react"></main>
Lodash's cloneDeep is way more simple to use. It performs a deep cloning, so it is a robust option, if you have a fairly complex state with multi-level objects or arrays inside. Just cloneDeep() the top-level state property, mutate the cloned part in whatever way you please, and setOuter() it back to the state.
3. immutability-helper
const App = () => {
const [outer, setOuter] = React.useState({ inner: 'initial value' })
React.useEffect(() => {
const update = immutabilityHelper
console.log('Before the deep cloning and updating:', outer.inner) // initial value
const newOuter = update(outer, { inner: { $set: 'updated value' } })
console.log('After the cloning and updating, the value in the state is still:', outer.inner) // initial value
setOuter(newOuter)
}, [])
console.log('In render:', outer.inner)
return (
<section>Inner property: <i>{outer.inner}</i></section>
)
}
ReactDOM.render(
<App />,
document.getElementById('react')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.10.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.10.2/umd/react-dom.production.min.js"></script>
<script src="https://wzrd.in/standalone/immutability-helper#3.0.0"></script>
<main id="react"></main>
immutability-helper takes it to a whole new level, and the cool thing about it is that it can not only $set values to state items, but also $push, $splice, $merge (etc.) them. Here is a list of commands available.
Side notes
Again, keep in mind, that setOuter only modifies the first-level properties of the state object (outer in these examples), not the deeply nested (outer.inner). If it behaved in a different way, this question wouldn't exist.
Which one is right for your project?
If you don't want or can't use external dependencies, and have a simple state structure, stick to Object.assign.
If you manipulate a huge and/or complex state, Lodash's cloneDeep is a wise choice.
If you need advanced capabilities, i.e. if your state structure is complex and you need to perform all kinds of operations on it, try immutability-helper, it's a very advanced tool which can be used for state manipulation.
...or, do you really need to do this at all?
If you hold a complex data in React's state, maybe this is a good time to think about other ways of handling it. Setting a complex state objects right in React components is not a straightforward operation, and I strongly suggest to think about different approaches.
Most likely you better be off keeping your complex data in a Redux store, setting it there using reducers and/or sagas and access it using selectors.
I had the same problem. Here's a simple solution that works !
const newItems = [...this.state.items];
newItems[item] = value;
this.setState({ items:newItems });
According to the React documentation on setState, using Object.assign as suggested by other answers here is not ideal. Due to the nature of setState's asynchronous behavior, subsequent calls using this technique may override previous calls causing undesirable outcomes.
Instead, the React docs recommend to use the updater form of setState which operates on the previous state. Keep in mind that when updating an array or object you must return a new array or object as React requires us to preserve state immutability. Using ES6 syntax's spread operator to shallow copy an array, creating or updating a property of an object at a given index of the array would look like this:
this.setState(prevState => {
const newItems = [...prevState.items];
newItems[index].name = newName;
return {items: newItems};
})
First get the item you want, change what you want on that object and set it back on the state.
The way you're using state by only passing an object in getInitialState would be way easier if you'd use a keyed object.
handleChange: function (e) {
item = this.state.items[1];
item.name = 'newName';
items[1] = item;
this.setState({items: items});
}
Don't mutate the state in place. It can cause unexpected results. I have learned my lesson! Always work with a copy/clone, Object.assign() is a good one:
item = Object.assign({}, this.state.items[1], {name: 'newName'});
items[1] = item;
this.setState({items: items});
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
Use array map with arrow function, in one line
this.setState({
items: this.state.items.map((item, index) =>
index === 1 ? { ...item, name: 'newName' } : item,
)
})
Sometimes in React, mutating the cloned array can affect the original one, this method will never cause mutation:
const myNewArray = Object.assign([...myArray], {
[index]: myNewItem
});
setState({ myArray: myNewArray });
Or if you just want to update a property of an item:
const myNewArray = Object.assign([...myArray], {
[index]: {
...myArray[index],
prop: myNewValue
}
});
setState({ myArray: myNewArray });
As none of the above options was ideal to me I ended up using map:
this.setState({items: this.state.items.map((item,idx)=> idx!==1 ?item :{...item,name:'new_name'}) })
Mutation free:
// given a state
state = {items: [{name: 'Fred', value: 1}, {name: 'Wilma', value: 2}]}
// This will work without mutation as it clones the modified item in the map:
this.state.items
.map(item => item.name === 'Fred' ? {...item, ...{value: 3}} : item)
this.setState(newItems)
It's really simple.
First pull the entire items object from state, updated the part of the items object as desired, and put the entire items object back in state via setState.
handleChange: function (e) {
items = Object.assign(this.state.items); // Pull the entire items object out. Using object.assign is a good idea for objects.
items[1].name = 'newName'; // update the items object as needed
this.setState({ items }); // Put back in state
}
Found this surprisingly hard and none of the ES6 spread magic seemed to work as expected.
Was using a structure like this to get rendered element properties for layout purposes.
found using the update method from immutability-helper to be the most straight forward one in this simplified example:
constructor(props) {
super(props)
this.state = { values: [] }
this.updateContainerState = this.updateContainerState.bind(this)
}
updateContainerState(index, value) {
this.setState((state) => update(state, { values: { [index]: { $set: value } } }))
}
as adapted from https://github.com/kolodny/immutability-helper#computed-property-names
of the to be updated array member is a more nested complex object use the appropriate deep copy method based on complexity.
There are surely better ways to handle layout parameters, but this is about how to handle arrays. The relevant values for each child element could also be computed outside of them, but I found it more convenient to pass containerState down, so they childs can fetch properties at will and Update the parent state array at their given index.
import React from 'react'
import update from 'immutability-helper'
import { ContainerElement } from './container.component.style.js'
import ChildComponent from './child-component'
export default class ContainerComponent extends React.Component {
constructor(props) {
super(props)
this.state = { values: [] }
this.updateContainerState = this.updateContainerState.bind(this)
}
updateContainerState(index, value) {
this.setState((state) => update(state, { values: { [index]: { $set: value } } }))
}
// ...
render() {
let index = 0
return (
<ContainerElement>
<ChildComponent
index={index++}
containerState={this.state}
updateContainerState={this.updateContainerState}
/>
<ChildComponent
index={index++}
containerState={this.state}
updateContainerState={this.updateContainerState}
/>
</ContainerElement>
)
}
}
#JonnyBuchanan's answer works perfectly, but for only array state variable. In case the state variable is just a single dictionary, follow this:
inputChange = input => e => {
this.setState({
item: update(this.state.item, {[input]: {$set: e.target.value}})
})
}
You can replace [input] by the field name of your dictionary and e.target.value by its value. This code performs the update job on input change event of my form.
Use the event on handleChange to figure out the element that has changed and then update it. For that you might need to change some property to identify it and update it.
See fiddle https://jsfiddle.net/69z2wepo/6164/
I would move the function handle change and add an index parameter
handleChange: function (index) {
var items = this.state.items;
items[index].name = 'newName';
this.setState({items: items});
},
to the Dynamic form component and pass it to the PopulateAtCheckboxes component as a prop. As you loop over your items you can include an additional counter (called index in the code below) to be passed along to the handle change as shown below
{ Object.keys(this.state.items).map(function (key, index) {
var item = _this.state.items[key];
var boundHandleChange = _this.handleChange.bind(_this, index);
return (
<div>
<PopulateAtCheckboxes this={this}
checked={item.populate_at} id={key}
handleChange={boundHandleChange}
populate_at={data.populate_at} />
</div>
);
}, this)}
Finally you can call your change listener as shown below here
<input type="radio" name={'populate_at'+this.props.id} value={value} onChange={this.props.handleChange} checked={this.props.checked == value} ref="populate-at"/>
If you need to change only part of the Array,
You've a react component with state set to.
state = {items: [{name: 'red-one', value: 100}, {name: 'green-one', value: 999}]}
It's best to update the red-one in the Array as follows:
const itemIndex = this.state.items.findIndex(i=> i.name === 'red-one');
const newItems = [
this.state.items.slice(0, itemIndex),
{name: 'red-one', value: 666},
this.state.items.slice(itemIndex)
]
this.setState(newItems)
or if you have a dynamically generated list and you don't know the index but just have the key or id:
let ItemsCopy = []
let x = this.state.Items.map((entry) =>{
if(entry.id == 'theIDYoureLookingFor')
{
entry.PropertyToChange = 'NewProperty'
}
ItemsCopy.push(entry)
})
this.setState({Items:ItemsCopy});
Try with code:
this.state.items[1] = 'new value';
var cloneObj = Object.assign({}, this.state.items);
this.setState({items: cloneObj });
Following piece of code went easy on my dull brain. Removing the object and replacing with the updated one
var udpateditem = this.state.items.find(function(item) {
return item.name == "field_1" });
udpateditem.name= "New updated name"
this.setState(prevState => ({
items:prevState.dl_name_template.filter(function(item) {
return item.name !== "field_1"}).concat(udpateditem)
}));
How about creating another component(for object that needs to go into the array) and pass the following as props?
component index - index will be used to create/update in array.
set function - This function put data into the array based on the component index.
<SubObjectForm setData={this.setSubObjectData} objectIndex={index}/>
Here {index} can be passed in based on position where this SubObjectForm is used.
and setSubObjectData can be something like this.
setSubObjectData: function(index, data){
var arrayFromParentObject= <retrieve from props or state>;
var objectInArray= arrayFromParentObject.array[index];
arrayFromParentObject.array[index] = Object.assign(objectInArray, data);
}
In SubObjectForm, this.props.setData can be called on data change as given below.
<input type="text" name="name" onChange={(e) => this.props.setData(this.props.objectIndex,{name: e.target.value})}/>
this.setState({
items: this.state.items.map((item,index) => {
if (index === 1) {
item.name = 'newName';
}
return item;
})
});
handleChanges = (value, key) => {
// clone the current State object
let cloneObject = _.extend({}, this.state.currentAttribute);
// key as user.name and value= "ABC" then current attributes have current properties as we changes
currentAttribute[key] = value;
// then set the state "currentAttribute" is key and "cloneObject" is changed object.
this.setState({currentAttribute: cloneObject});
and Change from Text box add onChange event
onChange = {
(event) => {
this.handleChanges(event.target.value, "title");
}
}
Try this it will definetly work,other case i tried but didn't work
import _ from 'lodash';
this.state.var_name = _.assign(this.state.var_name, {
obj_prop: 'changed_value',
});

Categories