I would like to add or delete object to another object through react state. How can I achieve this?
code is like this:
const [ stateObj, setStateObj ] = usetState({
obj1: {},
obj2: {},
obj3: {}
})
I want to add some objects temp1,temp2,temp3,... inside obj1, such as:
setState({ ...stateObj, obj1: {...obj1,temp1} })
setState({ ...stateObj, obj1: {...obj1,temp2} })
...
but this seems not correct, this keeps obj1 one item only
how can I add temp1,temp2,... into obj1 by state?
and also the method for delete temp1, temp2,...?
be careful we should copy the state first:
Never mutate state directly, as calling setState() afterwards may replace the mutation you made. Treat state as if it were immutable.
const temp1 = { a: 1 };
const temp2 = { b: 2, c: 3 };
const prevState={...stateObj};
const newObj1 = { ...prevState.obj1, ...temp1, ...temp2 };
setStateObj({ ...prevState, obj1: newObj1 });
console.log(stateObj);
here is an example just with javascript
const stateObj = {
obj1: {},
obj2: {},
obj3: {}
};
const temp1={a:1};
const temp2={b:2,c:3};
const newObj1={...stateObj.obj1,...temp1,...temp2};
const updatedState={...stateObj,obj1:newObj1}
console.log(updatedState)
You're calling setState simultaneously, so the state is updated only once with the last value. setState is batched together as it is not synchronous. You have to update the state with the previous state
You could try this code:
setStateObj(prevState = > {
return {
...prevState,
obj1: {
...obj1,
temp1
}
}
})
Related
I have a dictionary named CarValues in my code which contains following data:
CarValues is a dictionary initialized in the state.
dictionary: CarValues
key ==> string
Value ==> Array
key => Honda, Value => white, yellow, red, orange
key => Toyota, Value => white, yellow, green, black
Key => Volkswagen Value => 123, 456, 343
I would like to delete Honda and its value completely from CarValues. Though, I see few similar questions, I couldn't find the best solution for this question.
How can I remove an attribute from a Reactjs component's state object
This should solve your issue
yourMethod(key) {
const copyCarValues= {...this.state.CarValues}
delete copyCarValues[key]
this.setState({
CarValues: copyCarValues,
})
}
I believe in order to truly do this without mutating the state, you will need to re-create the entire state like so.
class Test extends React.Component {
state = {
thingToDelete: {},
otherStuff: {}
};
deleteThingToDelete = () => {
const {thingToDelete, ...state} = this.state;
this.setState(state);
}
}
Using the spread operator, we achieve a shallow clone, so be wary about that. The other option is to use Object.assign but that will also only offer a shallow clone but you will achieve much better browser support.
Probably arriving here a bit late, but here is a way of doing this with hooks and without actually mutating the previous state.
const sampleItems = {
'key1': { id: 1, name: 'test'},
'key2': { id: 2, name: 'test2'},
}
const Test = props => {
const [items, setItems] = useState(sampleItems);
deleteItemFromStateObject = itemKey => {
setItems(({[itemKey]: toDelete, ...rest}) => rest);
}
}
The easiest way to do this would be:
const carValues = Object.assign({}, this.state.carValues)
delete carValues[key]
this.setState({ carValues })
You can use Underscore.js or Lodash http://underscorejs.org/#omit
_.omit(copyCarValues, 'Honda');
First Initialise Array Globally
var dict = []
Add Object into Dictionary
dict.push(
{ key: "One",value: false},
{ key: "Two",value: false},
{ key: "Three",value: false});
Output :
[0: {key: "One", value: false},
1: {key: "Two", value: false},
2: {key: "Three", value: false}]
Update Object from Dictionary
Object.keys(dict).map((index) => {
if (index == 1){
dict[index].value = true
}
});
Output :
[0: {key: "One", value: false},
1: {key: "Two", value: true},
2: {key: "Three", value: false}]
Delete Object from Dictionary
Object.keys(dict).map((index) => {
if (index == 2){
dict.splice(index)
}
});
Output :
[0: {key: "One", value: false},
1: {key: "Two", value: true}]
Here is another simple enough solution to achieve this.
const myCarsValueInState = this.state.myCarsValueInState;
Object.keys(myCarsValueInState).map((index) => {
myCarsValueInState[index] = undefined; // you can update on any condition if you like, this line will update all dictionary object values.
return myCarsValueInState;
});
Simple enough.
state default values
state = {
moveType: {
value: 0,
open: false,
completed: false
}
};
// callback to update new state
let step = 'moveType';
let val = 3; // new value
let newObj = { ...this.state[step], value: val };
console.log(newObj);
this.setState({[step]: newObj }, function () {console.log(this.state);});
console.log(newObj) shows new values proper, but this.state still shows old values.. can you tell me what i'm doing wrong?
Setting state in react is pretty sensitive thing to do.
The best practices I've used to is always control object deep merge manually and use this.setState(state => { ... return new state; }) type of call, like in this example:
this.setState(state => ({
...state,
[step]: { ...(state[step] || {}), ...newObj },
}), () => console.log(this.state));
SNIPPET UPDATE start
[step]: { ...state[step], ...newObj }
Changed to:
[step]: { ...(state[step] || {}), ...newObj }
To deal correctly with cases, when state does not have this step key yet
SNIPPET UPDATE end
Thing is, that when you use this.state (in let newObj = { ...this.state[step]), it might have an outdated value, due to some pending (not merged yet) changes to the state, that you've called just couple of milliseconds ago.
Thus I recommend to use callback approach: this.setState(state => { ... use state and return new state;}) which guarantees that the state you use has latest value
I am updating an object within an array in React state using immutability helper.
The object I want to modify is nested:
this.state = {
a: {
b: [{ c: '', d: ''}, ...]
}
}
I want to update the prop c within the nth element of b using immutability helper.
The equivalent code without the immutability helper is:
const newState = Object.assign({}, this.state);
newState.a = Object.assign({}, newState.a);
newState.a.b = newState.a.b.slice();
newState.a.b[n] = Object.assign({}, newState.a.b[n]);
newState.a.b[n].c = 'new value';
this.setState({ newState });
I know the above code is a bit ugly. I am assuming the code using immutability helper will solve my problem. Thanks
One way to do it would be using $set
let index = 0;
let newState = update(this.state, {
a: {
b: {
[index]: {
c: { $set: "new value"}
}
}
}
});
this.setState(newState);
jsfiddle
Im importing update from immutability helper here :)
this.state = {
a: {
b: [{ c: '', d: ''}, ...]
}
}
this.setState((prevState, props) => update(prevState, {
a: {
b: {
$apply: b => b.map((item, ii) => {
if(ii !== n) return item;
return {
...item,
c: 'new value'
}
})
}
}
}))
I am using Redux. In my reducer I'm trying to remove a property from an object like this:
const state = {
a: '1',
b: '2',
c: {
x: '42',
y: '43'
},
}
And I want to have something like this without having to mutate the original state:
const newState = {
a: '1',
b: '2',
c: {
x: '42',
},
}
I tried:
let newState = Object.assign({}, state);
delete newState.c.y
but for some reasons, it deletes the property from both states.
Could help me to do that?
How about using destructuring assignment syntax?
const original = {
foo: 'bar',
stack: 'overflow',
};
// If the name of the property to remove is constant
const { stack, ...withoutFirst } = original;
console.log(withoutFirst); // Will be { "foo": "bar" }
// If the name of the property to remove is from a variable
const key = 'stack'
const { [key]: value, ...withoutSecond } = original;
console.log(withoutSecond); // Will be { "foo": "bar" }
// To do a deep removal with property names from variables
const deep = {
foo: 'bar',
c: {
x: 1,
y: 2
}
};
const parentKey = 'c';
const childKey = 'y';
// Remove the 'c' element from original
const { [parentKey]: parentValue, ...noChild } = deep;
// Remove the 'y' from the 'c' element
const { [childKey]: removedValue, ...childWithout } = parentValue;
// Merge back together
const withoutThird = { ...noChild, [parentKey]: childWithout };
console.log(withoutThird); // Will be { "foo": "bar", "c": { "x": 1 } }
I find ES5 array methods like filter, map and reduce useful because they always return new arrays or objects. In this case I'd use Object.keys to iterate over the object, and Array#reduce to turn it back into an object.
return Object.assign({}, state, {
c: Object.keys(state.c).reduce((result, key) => {
if (key !== 'y') {
result[key] = state.c[key];
}
return result;
}, {})
});
You can use _.omit(object, [paths]) from lodash library
path can be nested for example: _.omit(object, ['key1.key2.key3'])
Just use ES6 object destructuring feature
const state = {
c: {
x: '42',
y: '43'
},
}
const { c: { y, ...c } } = state // generates a new 'c' without 'y'
console.log({...state, c }) // put the new c on a new state
That's because you are copying the value of state.c to the other object. And that value is a pointer to another javascript object. So, both of those pointers are pointing to the same object.
Try this:
let newState = Object.assign({}, state);
console.log(newState == state); // false
console.log(newState.c == state.c); // true
newState.c = Object.assign({}, state.c);
console.log(newState.c == state.c); // now it is false
delete newState.c.y;
You can also do a deep-copy of the object. See this question and you'll find what's best for you.
How about this:
function removeByKey (myObj, deleteKey) {
return Object.keys(myObj)
.filter(key => key !== deleteKey)
.reduce((result, current) => {
result[current] = myObj[current];
return result;
}, {});
}
It filters the key that should be deleted then builds a new object from the remaining keys and the initial object. The idea is stolen from Tyler McGinnes awesome reactjs program.
JSBin
function dissoc(key, obj) {
let copy = Object.assign({}, obj)
delete copy[key]
return copy
}
Also, if looking for a functional programming toolkit, look at Ramda.
As of 2019, another option is to use the Object.fromEntries method. It has reached stage 4.
const newC = Object.fromEntries(
Object.entries(state.c).filter(([key]) => key != 'y')
)
const newState = {...state, c: newC}
The nice thing about it is that it handles integer keys nicely.
You may use Immutability helper in order to unset an attribute, in your case:
import update from 'immutability-helper';
const updatedState = update(state, {
c: {
$unset: ['y']
}
});
It's easy with Immutable.js:
const newState = state.deleteIn(['c', 'y']);
description of deleteIn()
Here's an easy 1-liner you can use that allows you to partially apply the prop you want to remove. This makes it easy to pass to Array.map.
const removeProp = prop => ({ [prop]: _, ...rest }) => ({ ...rest })
Now you can use it like this:
const newArr = oldArr.map(removeProp('deleteMe'))
The issue you are having is that you are not deep cloning your initial state. So you have a shallow copy.
You could use spread operator
const newState = { ...state, c: { ...state.c } };
delete newState.c.y
Or following your same code
let newState = Object.assign({}, state, { c: Object.assign({}, state.c) });
delete newState.c.y
I normally use
Object.assign({}, existingState, {propToRemove: undefined})
I realise this isn't actually removing the property but for almost all purposes 1 its functionally equivalent. The syntax for this is much simpler than the alternatives which I feel is a pretty good tradeoff.
1 If you are using hasOwnProperty(), you will need to use the more complicated solution.
I use this pattern
const newState = Object.assign({}, state);
delete newState.show;
return newState;
but in book i saw another pattern
return Object.assign({}, state, { name: undefined } )
utility ;))
const removeObjectField = (obj, field) => {
// delete filter[selectName]; -> this mutates.
const { [field]: remove, ...rest } = obj;
return rest;
}
action type
const MY_Y_REMOVE = 'MY_Y_REMOVE';
action creator
const myYRemoveAction = (c, y) => {
const result = removeObjectField(c, y);
return dispatch =>
dispatch({
type: MY_Y_REMOVE,
payload: result
})
}
reducer
export default (state ={}, action) => {
switch (action.type) {
case myActions.MY_Y_REMOVE || :
return { ...state, c: action.payload };
default:
return state;
}
};
As hinted in some of the answers already, it's because you are trying to modify a nested state ie. one level deeper. A canonical solution would be to add a reducer on the x state level:
const state = {
a: '1',
b: '2',
c: {
x: '42',
y: '43'
},
}
Deeper level reducer
let newDeepState = Object.assign({}, state.c);
delete newDeepState.y;
Original level reducer
let newState = Object.assign({}, state, {c: newDeepState});
Use a combination of Object.assign, JSON.parse and JSON.stringify
const obj1 = { a: "a", b: "b" };
const obj2 = { c: "c", a: undefined };
const merged = Object.assign({}, obj1, obj2);
const sanitized = JSON.parse(JSON.stringify(merged));
console.log(sanitized); // -> { b: "b", c: "c" }
In my case, I'm using React.js and I would like to dynamically update the values in the deployOptions object.
For example -
initial state looks like:
getInitialState() {
return {
deployOptions: {
config: null,
action: 'deploy',
env: 'qa'
}
}
}
Obviously this is not correct - but this is what I'm trying to achieve
configOptionChange(option) {
// option -> { key: 'env', value: 'prod' }
this.setState({
[deployOptions.option.key]: option.value
});
}
so that my state would then be
{
deployOptions: {
config: null,
action: 'deploy',
env: 'prod' // only this changes
}
}
It's not especially pretty, but I think this is the best you can do with ES6:
configOptionChange({ key, value }) {
this.setState({
...this.state,
deployOptions: {
...this.state.deployOptions,
[key]: value
}
});
}
It's basically equivalent to your own Object.assign solution but using the ES6 spread (...) operator (and argument destructuring for good measure).
Here's a second option that isn't as clever but feels a little cleaner to me:
configOptionChange({ key, value }) {
const { deployOptions: prevDeployOptions } = this.state;
const deployOptions = { ...prevDeployOptions, [key]: value };
this.setState({ ...this.state, deployOptions });
}
Just like these are nested objects, you can nest ES6 Computed Property Name like this:
[yourNestedObject]: {...yourNestedObject, [nestedObjectProperty]: value}
Here is an example function that will update an object's properties and the properties of nested objects. Where prop is the property to change, value is the value to assign, and propObj is the name of your nested object. I used useState hook for this.
const [obj, setObj] = useState({
prop1: '',
prop2: '',
nestedObj: {
prop1: '',
prop2: ''
}
});
const updateObj = (prop, value, propObj=false) => {
if (propObj) {
setObj({...obj, [propObj]: {...obj[propObj], [prop]: value}})
} else {
setObj({...obj, [prop]: value})
}
}
I think this might do the trick - but if anyone has a better solution?
configOptionChange(option) {
this.setState({
deployOptions: Object.assign({}, this.state.deployOptions, {[option.key]: option.val})
});
}
I'm using reduce to update the state of a component from a passed string of path properties:
handleChangeNested(event) {
const target = event.target; //an <input /> tag
let newState = { ...this.state };
let valuePath = target.name.split('.'); //the input's name is the the keys of the state object like 'group1.input1'
// Move down in the state object until we get to the 'bottom' property and change its value
// If the object does not have the properties we create them on the fly
valuePath.reduce((acc, key, index, path) => {
if (index === path.length - 1) {
acc[key] = target.value;
}
acc[key] = acc[key] || {};
return acc[key];
}, newState);
this.setState(newState);
}
The best solution I know would be to use "immutable" library.
configOptionChange(option) {
// option -> { key: 'env', value: 'prod' }
this.setState(state => setIn(state, ['deployOptions', option.key], option.value));
}