Last active
May 21, 2018 18:15
-
-
Save CWSites/dc01ad3715ed52a6ebcd1a2ba335db6f to your computer and use it in GitHub Desktop.
Set Interval from Parent for Child Component API Call
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// CHART COMPONENT | |
state = { | |
rawData: {}, | |
chartData: [], | |
interval: this.props.state.refresh, | |
intervalId: setInterval(async() => { | |
this.fetchData(url, request); | |
}, this.props.state.refresh) | |
} | |
componentDidMount() { | |
// initially load API data | |
this.fetchData(url, request); | |
} | |
fetchData = (url, request) => { | |
fetch(url, { | |
body: JSON.stringify(request), | |
method: 'POST', | |
headers: new Headers({ | |
'x-lwlauth': lwlauth, | |
'content-type': 'application/json' | |
}) | |
}) | |
.then(response => response.json() | |
.then(data => this.loadData(data)) | |
.catch(error => console.error(`error requesting ${request} from ${url}`))); | |
} | |
loadData = (data) => { | |
if (data !== undefined) { | |
let chartData = []; | |
let chartLabels = []; | |
for(let i=0; i < data.rows.length; i++){ | |
chartData.push(data.rows[i].values[1]); | |
chartLabels.push(formatMoment(data.rows[i].values[0])); | |
} | |
this.setState({ | |
rawData: data, | |
chartLabels: chartLabels, | |
chartData: chartData | |
}); | |
} else { | |
console.error(`error requesting ${request} from ${url}`); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// PARENT COMPONENT | |
// set default filters using state | |
state = { | |
refresh: 30000 // refresh every in milliseconds | |
} | |
// on change, update the refresh rate | |
updateRefresh = (el) => { | |
const refresh = this.state.refresh; | |
const value = parseInt(el.currentTarget.value, 10); | |
if(value && refresh !== value) { | |
this.setState({ | |
refresh: value | |
}); | |
} | |
} | |
render() { | |
return ( | |
<label className="control-label">Refresh Every</label> | |
<Select2 className="form-control" ref="refresh" | |
onChange={this.props.updateRefresh.bind(this)} | |
value={this.props.state.refresh} | |
data={[ | |
{ text: '30 Seconds', id: 1, value: 30000 }, | |
{ text: '1 Minute', id: 2, value: 60000 }, | |
{ text: '5 Minutes', id: 3, value: 300000 } | |
]} | |
/> | |
<Chart state={this.state} /> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment