Reputation: 121
My goal is to display 3 cards with some numbers that updates every second. I have an array of objects that have name, numbers and icon properties. I can't figure out how to update only the numbers, not the rest of the properties. Here's my code:
const initialStats = [
{ name: "Twitter", numbers: 10345, icon: "twitter" },
{ name: "Facebook", numbers: 8739, icon: "facebook f" },
{ name: "Google+", numbers: 2530, icon: "google plus g" }
];
export default class Social extends React.Component {
state = {
stats: initialStats
};
componentDidMount() {
this.timer = setInterval(() => {
this.setState(prevState => ({
stats: [...prevState.stats]
}));
}, 1000);
}
componentWillUnmount() {
clearInterval(this.timer);
}
render() {
const { stats, number } = this.state;
return (
<div className="social">
<h3 className="social__title">Social</h3>
<div className="social__data">
{stats.map(stat => {
return (
<div key={stat.name} className="social__data__stats">
<div className="social__data__stats--icon">
<Icon name={stat.icon} size="big" />
</div>
<div className="social__data__stats--content">
<h4 className="social__data__stats--content--name">
{stat.name}
</h4>
<p className="social__data__stats--content--numbers">
{stat.numbers}
</p>
</div>
</div>
);
})}
</div>
</div>
);
}
}
Upvotes: 2
Views: 130
Reputation: 311
componentDidMount() {
this.timer = setInterval(() => {
const stats = this.state.stats.map(item => {
return { ...item, numbers: /* your number */ }
})
this.setState({ stats });
}, 1000);
}
Upvotes: 0
Reputation: 116
componentDidMount() {
this.timer = setInterval(() => {
var stats = JSON.parse(JSON.stringify(this.state.stats)); // shallow copying the stats state variable
stats = stats.map((value,index,arr)=>{
value.numbers = 12; // Give any value you want ,i gave 12 for example
})
this.setState({stats});
}, 1000);
}
correct me ,if anything is wrong. Thanks, Naveen.N.D
Upvotes: 0
Reputation: 59491
Try this:
componentDidMount() {
this.timer = setInterval(() => {
this.setState(prevState => ({
stats: prevState.stats.map(stat => ({...stat, numbers: Math.random() * 10000})
}));
}, 1000);
}
Using the spread operator, you can set the value of some specific properties and copy the rest. The snippet above will give you a random number between 0 - 10000.
Upvotes: 3
Reputation: 5895
something like this?
this.timer = setInterval(() => {
this.setState(prevState => ({
prevState.stats[0].numbers = 1000;
prevState.stats[1].numbers = 2000;
prevState.stats[2].numbers = 3000;
stats: [...prevState.stats]
}));
}, 1000);
Upvotes: 0