Reputation: 365
I want to use Set object to store unique values. but by default we can't use Set.map() to make a loop on Set values in React and JSX.
But with this trick I can store Set into states and make a loop on that :
<ul>
{
Array.from(this.state.mySet).map((item, index) => (
<li key={index}>{item}</li>
))
}
</ul>
So, Is the above trick correct and best practice to handle this issue ?
In terms of performance and concepts ...
Thanks
Upvotes: 1
Views: 1228
Reputation: 3774
This is fine but react identifies state changes only if the state property was replaced, and not mutated/shallow compare. You'll have to use the old Set to create a new Set and then apply changes to it. That way you won't have to force update the state.
export default class Test extends React.Component {
constructor(props) {
super(props);
this.state = {
mySet: new Set()
}
this.add = this.add.bind(this);
}
add(item) {
this.setState(({ mySet }) => ({
mySet: new Set(mySet).add(item)
}));
}
/*
.
.
. Other code
.
. */
}
Hope this helps !
Upvotes: 1