I'm putting together a cryptocurrency app as an experiment and I'm pulling data from an API. I've managed to get all the data to display nicely and search for a price change every two seconds but I'd like to temporarily add a class to the updated DOM element when the price changes, red if down and green if up. I'm currently mapping out each item from the API and only wish to add the required class to the updated item (currency) in the DOM. Not all items.
Please see my code below:
import React, { Component } from "react";
import { Link } from "react-router-dom";
import "./home.scss";
class Home extends Component {
// Create initial state and pass props
constructor(props) {
super(props);
this.state = {
isLoading: true,
coins: []
}
}
// Custom fetch data method
fetchData() {
// Fetch data
fetch('http://coincap.io/front')
// Turn response into JSON
.then(response => response.json())
// Take parsedJSON and log results
// Create individual object for each of the users
.then(parsedJSON => parsedJSON.map(coin => (
{
long: `${coin.long}`,
short: `${coin.short}`,
price: `${coin.price}`
}
)))
// Overwrite empty array with new contacts
// Set array to contacts state and set isLoading to false
.then(coins => {
this.setState({
coins,
isLoading: false
})
})
// Catch the errors
.catch(error => console.log('parsing failed', error))
}
componentDidMount() {
setInterval(() => {
this.fetchData();
console.log('refreshed');
}, 2000);
}
render() {
const { isLoading, coins } = this.state;
return (
<div className="container__wrap container__wrap--home">
<div className={`content ${isLoading ? "is-loading" : ""}`}>
<div className="panel">
{
!isLoading && coins.length > 0
? coins.map(coin => {
// Destruct each of the items in let variable
let { long, short, price } = coin;
return (
<div className="panel__item" key={short}>
<p>Name: {long}</p>
<p>Short: {short}</p>
<p>Price: ${price}</p>
<Link className="button" to={`/${short}`}>
View Coin
</Link>
</div>
);
})
: null}
</div>
<div className="loader">
<div className="loader__icon" />
</div>
</div>
</div>
);
}
}
export default Home;
In short, I'd like to temporarily add a class to 'panel__item' each time that element updates.
Thanks in advance!