Skip to content

Commit 1abb0d3

Browse files
Copying elements to avoid mutating data structures
1 parent 4200b1c commit 1abb0d3

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

lib/state-api/lib/index.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,31 @@ class StateApi{
99
timestamp: new Date()};
1010
this.subscriptions ={};
1111
this.lastSubscriptionId=0;
12+
13+
//Simulating adding an article every minute
14+
setTimeout(() => {
15+
const fakeArticle = {
16+
...rawData.articles[0],
17+
id: 'fakeArticleId',
18+
};
19+
//This line mutates the state and that wont be recognized by the PureComponent
20+
// this.data.articles[fakeArticle.id] = fakeArticle;
21+
22+
//Hence instead of mutating the state we will copy
23+
//We are copying the current state and modifying that copy of the current state
24+
//So for the previous object and current object are different
25+
//Copying current data
26+
//Change the articles object
27+
//add new article
28+
this.data = {
29+
...this.data,
30+
articles: {
31+
...this.data.articles,
32+
[fakeArticle.id]: fakeArticle,
33+
},
34+
};
35+
this.notifySubscribers();
36+
}, 1000);
1237
}
1338

1439

0 commit comments

Comments
 (0)