Redux states are strangely changing - reactjs

I have 2 different states and one state contains a part of the second one. The fact is when the second state is changed, what is in the first state is also changed and I can't handle why.
Here is when I change the 2nd state :
case 'UPDATE_IMAGES':
return Object.assign({}, state, {
runes: updateChosenState(state, action)
});
export function updateChosenState(state,action){
const img = state.images.slice();
let e = action.e;
imga[].id_ = action.id;
return img;
}
The first state is accessing that way in the action then given to the reducer :
let img = getState().ImgReducer.images;
In the reducer I have some function to take when it's related :
const copy = images.slice();
items.image = copy[idGiven];
This line is changed whenever the images state is changed. Even by copy this is changed and I can't understand why. I just want to have a copy of this thing in my first state and for this state I don't care if images is changed after.
I feel that I'm directly accessing ImgReducer state so whenever it changes I have the update but I don't know how to avoid that.
Thanks you

Wen you use slice on an array, the returned array is not a real clone. Instead, you got a shallow copy of the array. Therefore, both, the copy and the original objects inside the array point to the same memory reference.
From the Array#slice docs on MDN:
To object references, slice copy the reference inside the new array. Both, the original and the new array are pointing to the same object. If an referenced object changes, the changes are visible for both arrays.
You can verify this with the following example:
const original = { src: 'foo' }
const images = [original]
const copy = images.slice()
original.src = 'baz'
console.log(copy)
Solution
You need to do a deep clone of the element. You can do this with the spread operator:
const original = { src: 'foo' }
const images = [original]
const copy = images.slice().map(o => ({ ...o }))
original.src = 'baz'
console.log(copy)
Another way to achieve the same goal is using JSON#stringify and JSON#parse:
const original = { src: 'foo' }
const images = [original]
const copy = JSON.parse(JSON.stringify(original))
original.src = 'baz'
console.log(copy)

Related

setState mutates the object reference

I am getting an object from parent component and setting to state. In child component I am updating the state, but the parent reference object values also changing instead of only state changes.
Parent Component has a huge object,
obj = {
values: {
per1: { name: "rsk" },
per2: { name: "ssk" },
}
}
Child Component:
const ChildComponent = ({obj}) => {
const [inp, setInp] = useState(obj.values);
const onChange = useCallback(({target}) => {
setInp((prev) => {
const nD = { ...prev };
//k1, k2 comes from some logic
nD[k1][k2] = target.value;
return nD;
})
}, []);
return (
Here the "inp" state is looped by objects and keys in text box to build a html form
)
}
Here the question is, why the core obj.values also changing on onChange setInp time. I dont want to disturb the obj.values untill i submit the form.
Because before submit the Form, I need to validate,
obj.values are equal or not to inp state values
Any idea on this.
The original object is changing because in JS, when you pass an array or an object in such a way, you are actually passing a reference to the original object/array.
Meaning that any changes made to the reference, will also affect the original.
In-order to avoid using the reference, you can copy the object/array and work with the copy instead.
There are a few ways of doing this, the simplest IMO is using the spread syntax.
Example:
const ChildComponent = ({obj}) => {
const [inp, setInp] = useState({...obj.values});
...
}
What we do here is "spread" the contents of obj.values into a new object, thus creating a new object and avoiding using the reference.
Note that the spread syntax only makes a shallow-copy, this isn't necessarily an issue unless you have some complex object which contains some other nested objects within it.
If you do need to perform a deep-copy, one simple way of doing it is via JSON methods.
Example:
const clone = JSON.parse(JSON.stringify(original));
First, this obj variable is incorrect because per1 is defined as object and object consist of key and value, but it is like a string array so please check that, and below is solution
In Child Component you should create a copy of that obj variable
const [inp, setInp] = useState(Object.assign({}, obj.values));
Bz if you set inp as the same variable it will pass the address of that variable so for that you need to create the copy and then you can change that inp.

React useReducer - update array of objects

I want to use React.useReducer to update state. My state is an array of objects. When update action is triggered, not only value from desired index is updated but all of them. I want to have updated only the value from indicated array index. How can I do that?
After I click button1, I want to get
[{"amount":null,"kcal":null,"name":null,"isPieceType":false},
{"amount":null,"kcal":null,"name":null,"isPieceType":false},
{"amount":null,"kcal":125,"name":null,"isPieceType":false},
{"amount":null,"kcal":null,"name":null,"isPieceType":false}]
instead of
[{"amount":null,"kcal":125,"name":null,"isPieceType":false},
{"amount":null,"kcal":125,"name":null,"isPieceType":false},
{"amount":null,"kcal":125,"name":null,"isPieceType":false},
{"amount":null,"kcal":125,"name":null,"isPieceType":false}]
I tried to copy state as const newState = [...state] and use lodash's cloneDeep. Below, link to jsfiddle with code to reproduce.
https://jsfiddle.net/wtj5eyfh/
Your initial state of ingredientsState has references to the same object called initialIngredient. That caused everything to update when one entry was updated. Even though
const stateToUpdate = [...state]; created a new array again all entries refers to the same object.
Fix
Change the following referenced array entries
const [ingredientsState, ingredientsDispatch] = React.useReducer(mealReducer, [
initialIngredient,
initialIngredient,
initialIngredient,
initialIngredient
]);
To be an array of copies of initialIngredient object (spread operator simply create clones of the referred object)
const [ingredientsState, ingredientsDispatch] = React.useReducer(mealReducer, [
{ ...initialIngredient },
{ ...initialIngredient },
{ ...initialIngredient },
{ ...initialIngredient }
]);
JS Fiddle

setState is not updating state at all

I cant figure out why my setStock function is not updating the state and not causing a re-render, while I have several other functions working just fine.
const addToStockOperation = async (addOperation) => {
const payload = {
...
};
const jwtToken = {
...
};
const addToStockOperationResult = await axios.put(`${apiEndpoint}/stock/addtoitem`, payload, jwtToken);
setStock((prevStock) => {
const indexOfModifiedStock = prevStock.findIndex((stock) => stock._id === addOperation.id);
console.log(prevStock[indexOfModifiedStock].operations.added.length);
prevStock[indexOfModifiedStock].operations.added = addToStockOperationResult.data.operations.added;
console.log(prevStock[indexOfModifiedStock].operations.added.length);
return prevStock;
});
};
Both console logs confirm that the modification of prevStock did happen, as the second console.log shows a length of +1 compared to the previous length, so that indicates that the desired part of prevStock was indeed updated, however, a re-render is not caused.
I have also tried making a copy of prevStock const stockCopy = {...prevStock}; and modifying the copy and returning the copy, but no change.
I have also tried simply to return 1; just to see if a re-render will get triggered, still nothing.
I have a few other similar functions that are working just fine and are causing a re-render as expected:
This one is working just fine for setting products:
const setProductsWrapper = async (product) => {
const addProductResult = await axios.post(
`${apiEndpoint}/product/one`,
payload,
token
);
addProductResult.data.name === product.name &&
setProducts((prevProducts) => [addProductResult.data, ...prevProducts]);
};
EDIT: I found the issue, silly me, stock is an array return [...stockCopy]; after modifying the copy, worked.
Returning prevStock is never going to work because it is the current state array (i.e. has reference equality with it) - you need to return a new array for a new render to be triggered. However, it seems likely that an issue is also arising with mutated state.
You're on the way there when you create the copy const stockCopy = [...prevStock], but the problem is that this only copies the state array to one level of depth. Any objects nested inside it, like .operations, will retain their reference equality to the objects in the original state array.
Mutating them directly means that when you return your copy, any effects which rely on a difference in reference equality between these sub-objects will not run because they are already equal. There is no diff-ing to be done.
To fix this you will have to deeply copy the relevant parts of the tree:
setStock((prevStock) => {
const stockCopy = [...prevStock];
const stockIndex = stockCopy.findIndex((stock) => stock._id === addOperation.id);
stockCopy[stockIndex] = {
...stockCopy[stockIndex],
operations: {
...stockCopy[stockIndex].operations,
added: addToStockOperationResult.data.operations.added
}
};
return stockCopy;
});
State mutation sandbox
This can get quite annoying (and potentially expensive) when the data structure is large enough. It's always better to avoid structures like this in immutable state if you can help it. Of course that's often not the case and there are tools to help deal with immutability that can cut down on bloated code if it starts to become an issue.

Why is useState hook changing another object without calling it?

I have a React component that retrieves data when it first loads.
const [data, setDate] = useState(null);
const [originalData, setOriginalData] = useState(null);
useEffect(() => {
async function fn() {
let res = await getObject();
setData({...res});
setOriginalData({...res});
}
fn();
}, [])
I call 2 different hooks to set the data and originalData states.
The purpose of this is so that I have an unchanged version of data that I can refer to for some of the logic in the component.
However when I make a change to the data state it seems to also be changing the originalData state as well without me calling anything.
const change() => {
let updatedData = {...data};
updatedData.someProperty = 'newValue';
setData(updatedData);
}
I would have expected that data now contains the property someProperty with the value newValue, and that originalData will be unchanged from the initial load.
But when I compare them, data and originalData both now have someProperty.
Can anyone point me in the right direction?
EDIT: add spread operator
Problem: Same Reference
The reason why changing data changes originalData is not because of React hooks, but because of the way objects behave in JavaScript. Though data and originalData are different, they are still referring to the same object (from res). So any changes made to either one of these will be reflected on the other, since they have same reference.
Solution: Clone
For this reason you should clone the data instead of directly assigning them.
// JSON
const originalData = JSON.parse(JSON.stringify(res))
// Object.assign
const originalData = Object.assign({}, res)
// Or spread opr
const originalData = { ...res }
// Then set the state
setOriginalData(originalData);
ES6 methods like Object.assign and spread operator does a shallow copy. If you need a deep copy and if your data doesn't have Dates, functions, undefined, Infinity, RegExps, Maps, Sets, Blobs, FileLists, ImageDatas, sparse Arrays, Typed Arrays or other complex types within your object, go for JSON parse, stringify.
Check out this question for more details about cloning in JavaScript

Redux key based array not triggering new props when added to 2nd time

I am dealing with Proposals and locations.
A location can have multiple proposals.
The component is passed a location object (below as passedProps) to show all the proposals for this location :
<Proposals location={ location } key={location.id}/>
Here is are my redux props :
const mapStateToProps = (state , passedProps) => {
return {
proposals : state.propertyProposals[passedProps.location.id]
};
};
when adding a new proposal, I want to store their ids by location, so in a addition to storing the proposal, I am storing their Ids, in an array keyed by location Id.
The first proposal added and refreshed with new props just fine, however even though the second one is successfully pushed to the array, this is not triggering new props, so it does not "refresh" -- If I leave the route and come back I see the new 2nd proposal (which did not show the first time)
Here is the PROPOSAL_CREATE action for a new Proposal.
type :'PROPOSAL_CREATE',
payload :
{'e7ef104e-19ed-acc8-7db5-8f13839faae3' : {
id : 'e7ef104e-19ed-acc8-7db5-8f13839faae3',
locationId: '41e9c5d8-a520-7e3b-939a-12f784d49712'
}
}
here is the case which handles it :
case 'PROPOSAL_CREATE':
{
const proposal = Object.values(action.payload)[0];
const locationId = proposal.locationId;
let newState = {...state}
if (locationId in newState) {
newState[locationId].push(proposal.id)
} else {
newState[locationId] = [proposal.id]
}
return newState
}
Is there an obvious reason I am not seeing the change in the component for the second entry?
Thanks
There is one issue here. Your store state is not immutable. You have used below line to make a copy:
let newState = {...state}
Here it does make copy of object but it's shallow copy, hence your array object in newState and state have the same reference. That's why redux doesn't identify the change in store and hence props are not updated in sequence.
You can clone your state by below methods:
let newState = JSON.parse(JSON.stringify(state));
OR if you use jQuery then:
let newState = $.extend(true, {}, state);
I think this will surely fix your issue.
Based on your reducer logic i think that you did not specify action type.
The one of the redux conventions is the action recognition based on type property.
I bet that you forgot to specify that property.
var properAction = {
type: 'PROPOSAL_CREATE',
payload: {
{
'e7ef104e-19ed-acc8-7db5-8f13839faae3': {
id: 'e7ef104e-19ed-acc8-7db5-8f13839faae3',
locationId: '41e9c5d8-a520-7e3b-939a-12f784d49712'
}
}
}
I would recommend you to write action creators it will reduce your place for typos like that.
Cheers!
2 things:
I forgot that Arrays of an original object are still by reference. So even after
let newState = {...state}
newState[locationId]
has the same reference as
state[locationId]
As a result my original statement was mutating the original state, not creating a newState
and so
newState[locationId].push(proposal.id)
needed to be
newState[locationId] = state[locationId].concat(proposal.id);
or es6
newState[locationId] = [ ...state[locationId] , proposal.id ] ;

Resources