I have a property of type object array in a React component. Using setState
I am trying to modify this property. But assigning a new value to this property inside
setState
has no effect. Please find below my sample code.
export const Test = ({
objectArray,
changeState = function (newoOjectArray) {
this.setState({objectArray: newoOjectArray});
console.log(JSON.stringify(objectArray)); // Doesn't reflect changes. Prints old objectArray
}
}) =>
(
<div>Some data</div>
)
Some user action will trigger a call to changeState(newoOjectArray)
. I am calling setState
inside changeState
function.
After calling setState
if I print the objectArray
variable to console it still holds old value.
How can I make setState
assign a new value to objectArray
.
Thanks
EDIT
I am aware that setState
is asynchronus and update to property may reflect after a delay.
But in case of example code above objectArray variable is never updated even after delay.
I have implemented componentWillReceiveProps(nextProps)
method and it gets called but it always receives old objectArray.
So I don't think the issue is related to setState
being asynchronous.
EDIT2
I have created an example app to demonstrate the issue I am facing. The example app runs fine locally and I can reproduce the issue.
But I am not being able to get the same example app code working in codepen
. it's giving me some 'unexpected token
' errors.
But I hope looking at the code will help understand my issue better.
The code is based on existing application structure.
Codepen example here.
In the code I have a Parent
and two children Child1
and Child2
.
In Parent
I have a function changeState
defined which I am passing to Child1
as property.
And to Child2
I am passing a 'name
' property from Parent
.
Clicking on 'Change Name
' button in Child1
triggers a call to changeState
function of Parent
.
Initial value of name in Parent
is 'Robert
'. changeState
is invoked from Child1
with new name value of 'Tom
'.
But in changeState
function assigning new value to 'name
' using setState
has no effect. I am calling a function to print the 'name
'
after setState
has completed but it prints old name value and NOT the new one assigned in setState
.