I creating a couple of lists items with financial data and I want to display a mini graph on the side using react-sparklines. So I'm trying to fetch the graph data when mapping the array since retrieving the data could take some time but it seems I can't get the graph component to update the prop value correctly.
How can I update the prop data in the Sparklines component once the data has been retreived from fetch?, is it possible?.
Here's a sample of my code
class CurrencyList extends Component {
currencyGraph(symbol) {
return fetch(baseURL, {
method: 'POST',
headers: {
'Authorization': 'JWT ' + token || undefined, // will throw an error if no login
},
body: JSON.stringify({'symbol': symbol})
})
.then(handleApiErrors)
.then(response => response.json())
.then(function(res){
if (res.status === "error") {
var error = new Error(res.message)
error.response = res.message
throw error
}
return res.graph_data
})
.catch((error) => {throw error})
}
render () {
topCurrencies.map((currency,i) => {
return (
<ListItem key={i} button>
<Sparklines data={this.currencyGraph(currency.symbol)} >
<SparklinesLine style={{ stroke: "white", fill: "none" }} />
</Sparklines>
<ListItemText primary={currency.symbol} />
</ListItem>
)
})
}
}
You can't return data from an asynchronous function like that. Instead, when your load request completes, set the data in the state which will trigger the component to render. Note that in the test case below, it renders a placeholder until the data is ready.
Item = props => <div>{props.name}</div>;
class Test extends React.Component {
state = {
data: ''
}
componentDidMount() {
// Simulate a remote call
setTimeout(() => {
this.setState({
data: 'Hi there'
});
}, 1000);
}
render() {
const { data } = this.state;
return data ? <Item name={this.state.data} /> : <div>Not ready yet</div>;
}
}
ReactDOM.render(
<Test />,
document.getElementById('container')
);