unexpected react component state value change - javascript

I am trying to update the state value but first I have loaded it in another varand after changes made on the new var it is going to setState and update the original state value. but unexpectedly changes made to the temp var already changes the component state value!
var postData = this.state.postData;
postData.likes = postData.likes + 1;
console.log(postData.likes, this.state.postData.likes);
the console.log values:
(1, 1)
(2, 2)
...

Since postData is an object, don't save it directly in another variable since that will create a reference to the one in the state, not a copy. And if it's a reference, changing one will change the other cos they're both pointing to the same object.
Make a copy of it first"
var postData = Object.assign({}, this.state.postData)
and then change it. Then when you're done, use setState({postData})

you should never ever mutate state, always use setState, and for copying object user spread notation "..."
this.setState(((prevState) => ({
postData:{
...prevState.postData,
likes: prevState.postData.likes + 1,
}
});

You can also use ES2018 spread notation like var postData = {...this.state.postData}; to clone the object and manipulate it before assigning back to state.

Related

React not registering state change when setting previous state with slight modifications as the new one

I have the following code :-
const [dice, setDice] = React.useState(allNewDice()) // Array of objects with the following properties: `value` (random digit between 1 and 6), `id` (unique id), `isHeld` (boolean)
function holdDice(id) {
const heldDie = dice.findIndex(die => die.id === id)
setDice(prevDice => {
prevDice[heldDie].isHeld = !prevDice[heldDie].isHeld
return prevDice
})
}
The function holdDice is working as expected. It updates prevDice's first element's isHeld property to the opposite of what was previously, as evident from logging it to the console. But the only problem is, the state is not getting updated.
So I tried making a copy of prevDice and then returning the copy (using the spread (...) operator) :-
const [dice, setDice] = React.useState(allNewDice()) // Array of objects with the following properties: `value` (random digit between 1 and 6), `id` (unique id), `isHeld` (boolean)
function holdDice(id) {
const heldDie = dice.findIndex(die => die.id === id)
setDice(prevDice => {
prevDice[heldDie].isHeld = !prevDice[heldDie].isHeld
return [...prevDice]
})
}
And this works perfectly.
Can anyone please explain why this behaviour? Why can't I return the previous state passed in to be set as the new state, even when I am not returning the previous state, exactly as it was?
I understand that it's expensive to re-render the component and that maybe React does not update the state when the previous and the new states are equal. But here, the previous and the new states are not equal.
My first guess was that it might have been related to React not deep checking whether the objets of the array prevDice have been changed or not, or something like that. So I created an array of Numbers and tried changing it's first element to some other number, but unless i returned a copy of the array, the state still did not change.
Any help would be greatly appreciated. Thank you!
The first time you call setDice() after the initial mount of your component or rerender, prevDice refers to the same array in memory that your dice state refers to (so prevDice === dice). It is not a unqiue copy of the array that you're able to modify. You can't/shouldn't modify it because the object that prevDice refers to is the same object that dice refers to, so you're actually modifying the dice state directly when you change prevState. Because of this, when the modified prevDice is used as the value for setDice(), React checks to see if the new state (which is prevState) is different from the current state (dice) to see if it needs to rerender. React does this equality check by using === (or more specifically Object.is()) to check if the two arrays/objects are the same, and if they are, it doesn't rerender. When React uses === between prevState and dice, JS checks to see if both variables are referring to the same arrays/objects. In our case they are, so React doesn't rerender. That's why it's very important to treat your state as immutable, which you can think of as meaning that you should treat your state as readonly, and instead, if you want to change it, you can make a "copy" of it and change the copy. Doing so will correctly tell React to use that new modified copy as the new state when passed into setDice().
Do note that while your second example does work, you are still modifying your state directly, and this can still cause issues. Your second example works because the array you are returning is a new array [], but the contents of that array (ie: the object references) still refers to the same objects in memory that your original dice state array referred to. To correctly perform your update in an immutable way, you can use something like .map(), which by nature returns a new array (so we'll rerender). When you map, you can return a new inner object when you find the one you want to update (rather than updating it directly). This way, your array is a new array, and any updated objects are also new:
function holdDice(id) {
setDice(prevDice => prevDice.map( // `.map()` returns a new array, so different to the `dice`/`prevDice` state
die => die.id === id
? {...die, isHeld: !die.isHeld} // new object, with overwritten property `isHeld`
: die
));
}
State doesn't update because you update it yourself in the setDice function.
dice and prevDice refer to the same object so it won't trigger a re-render.
const [dice, setDice] = React.useState(allNewDice())
function holdDice(id) {
const heldDie = dice.findIndex(die => die.id === id)
setDice(prevDice => {
// Create a copy of the dice
// Use whatever method you wish.Spread. JSON parse and stringify.
const currentDice = JSON.parse(JSON.stringify(prevDice))
currentDice[heldDie].isHeld = !prevDice[heldDie].isHeld
return currentDice
})
}

JavaScript Object giving different values when accessed directly

I am using React.js and I'm trying to update the state of my component when the props change. Before I explain the problem, I should mention that I have used both getDerivedStateFromProps and componentDidUpdate, the result is the same. The problem is that when I try to access the value of an element in prop, it differs whether I access the value directly or I use the object itself.
let userTickets = nextProps.support.userTickets;
// userTickets[0].messages is different from nextProps.support.userTickets[0].messages
below is the whole function code.
let userTickets = nextProps.support.userTickets;
console.log(nextProps.support.userTickets); // this contains the correct, updated value
for (let index = 0; index < userTickets.length; index++) {
let userTicket = userTickets[index];
console.log(userTicket); // this contains old incorrect value
}
Any guidance would be appreciated. Thanks.
Try to not directly assign props to variables because it may assign by reference instead of copy. Try this instead:
const userTickets = [ ...nextProps.support.userTickets ];
console.log(nextProps.support.userTickets);
userTickets.map(ticket => {
console.log(ticket);
});
Notice the 3 dot assignment of the array, this creates a new array with the values of the array that is "spread"

javascript: Update property value in Array() with index as parameter

Currently I've a react function that removes from a Array called rents the current rent perfect. The issue is that I need to update the rent row value called status and set property from 1 to 4 the code below works. I don't seem to get how to get the Index of rent to be able to update it.
removeItem (itemIndex) {
this.state.rents.splice(itemIndex, 1) // removes the element
this.setState({rents: this.state.rents}) // sets again the array without the value to the rent prop
console.log(itemIndex) // itemIndex
}
currently I'm adding this to the code to debug but get this error
console.log(this.state.rents[itemIndex].unique_key)
Stack Trace
TypeError: Cannot read property 'unique_key' of undefined
I need to be able to update the rent property value called status from 1 to 4 and setState again
To elaborate the comments, starting first with the most important:
Like #devserkan said, you should never mutate your state (and props), otherwise you start to see some really weird hard-to-make-sense bugs. When manipulating state, always create a copy of it. You can read more here.
Now for your question:
this.setState is asynchronous, so to get your state's updated value you should use a callback function
const rents = [...this.state.rents]; // create a copy
rents.splice(itemIndex, 1);
this.setState({ rents }, () => {
console.log(this.state.rents); // this will be up-to-date
});
console.log(this.state.rents); // this won't
Personally, I like using the filter method to remove items from the state and want to give an alternative solution. As we tried to explain in the comments and #Thiago Loddi's answer, you shouldn't mutate your state like this.
For arrays, use methods like map, filter, slice, concat to create new ones according to the situation. You can also use spread syntax to shallow copy your array. Then set your state using this new one. For objects, you can use Object.assign or spread syntax again to create new ones.
A warning, spread syntax and Object.assign creates shallow copies. If you mutate a nested property of this newly created object, you will mutate the original one. Just keep in mind, for this situation you need a deep copy or you should change the object again without mutating it somehow.
Here is the alternative solution with filter.
removeItem = itemIndex => {
const newRents = this.state.rents.filter((_, index) => index !== itemIndex);
this.setState({ rents: newRents });
};
If you want to log this new state, you can use a callback to setState but personally, I like to log the state in the render method. So here is one more alternative :)
render() {
console.log( this.state.rents );
...
}

Modifying state in React

I've read that it is not advisable to update state directly, e.g:
this.state.array = ['element'];
But, for example, consider this state:
this.state = {
array: [],
}
updateArray = element => {
temp = this.state.array;
temp.push(element);
this.setState({array: temp});
}
Isn't this essentialy the same as the first example? We are setting temp to point to this.state.array, thus mutating it and then overwriting it with this.setState().
I've seen this example in various tutorials, Wouldn't it be 'better' to make a copy of the array?
Check out the docs here, https://reactjs.org/docs/state-and-lifecycle.html.
According to the React team. Setting the state directly will not re-render a component. You must use setState.
As far as using a temp variable when setting state, that is used when something needs to be done to 'element' before setting the state variable. As setState can be called asynchronously. It is acceptable in your case to just do
updateArray = (element) => {
this.setState({ array: [ ...this.state.array, element ] });
}
Yes, you are right it's the same thing. You should read more about pass by value and pass by reference in JS.
When we say
let x = some.array
We are copying a reference(remember copy and paste as shortcut)? Both the things actually point to the same real thing and takes no extra space.
You should instead use some JS that can do this for you.
let x = some.array.slice()
This creates real copy of the array. On modern ES2015 you can do
let x = [...some.array]
a more elegent way.

Remove first item of array in react state

I know how to do this but trying this way and not sure why it wont work?
drawCard = () => {
const deck = this.state.cards;
deck.shift();
console.log(deck, 'deck'); //this is correctly logging one less everytime
this.setState({cards: deck})
}
cards is just an of objects
so even though the function is being called and the console log is working, why is it not updating state?
(console.log(state.cards.length) always returns 3)
Don't use methods that mutate the state (for instance, Array#shift). You could instead use Array#slice to return a shallow copy of a portion of the array:
drawCard = () => {
this.setState({ cards: this.state.cards.slice(1) })
}
The problem arises because you are directly modifying the state. Although you are assigning the state to 'deck' remember that in Javascript arrays and objects are references. So when you are modifying deck you are actually trying to modify the state itself. You can use other methods to create a copy of the states values and modify that.
You may find this helpful:
React - Changing the state without using setState: Must avoid it?
in react, you can't just change the state,
you need to create a copy of your state before updating,
the easiest way to do it is just replace this:
const deck = this.state.cards;
into this:
const deck = [...this.state.cards];

Categories