Seriously, I'm getting desperate finding what the issue is. I can't find the answer for days!
React.StrictMode
API causes our setState
to be called twice, right? If it produces an error, then it means that somewhere in our setState
callback is impure. So, which one is it?
setOrganization((initialValue) => {
const newOrganization = { ...initialValue };
const oldIssues = [...newOrganization.repository.issues.edges];
const newIssues = [...data.data.organization.repository.issues.edges];
newOrganization.repository.issues.edges = [...newIssues, ...oldIssues];
return newOrganization;
});
On the first call, oldIssues
is returning the expected value, for example, [{id: issue1}, {id: issue2}]
. newIssues
value is for example [{id: issue3}]
But on the second call, the oldIssues
strangely turn into the combination of oldIssues
and newIssues
. (second call, oldIssues
IS ALREADY [{id: issue1}, {id: issue2}, {id: issue3}]
).
Making the second newOrganization.repository.issues.edges
value has a doubled newIssues
. [{id: issue1}, {id: issue2}, {id: issue3}, {id: issue3}]
Full script can be found here, on line 101: https://pastebin.com/ugsrBRTM
Thanks to Nick Parsons' comment above, I just know that object spreading only performs a shallow copy. All I need to do is to change the copy method to deep copy.
I found the method here: What is the most efficient way to deep clone an object in JavaScript?