Skip to content

Instantly share code, notes, and snippets.

@CITGuru
Last active December 8, 2019 15:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CITGuru/66bf0eb52010dc7709d3317408114e50 to your computer and use it in GitHub Desktop.
Save CITGuru/66bf0eb52010dc7709d3317408114e50 to your computer and use it in GitHub Desktop.
ReactComponentExercise.js.txt (Original)
/**
* This React class is intended to query an endpoint that will return an alphanumeric string, after clicking a button.
* This component is passed a prop "apiQueryDelay", which delays the endpoint request by N milliseconds. There is a
* second button to disable this functionality and have the endpoint request run immediately after button click.
* This data is then to be displayed inside a simple container.
* The "queryAPI" XHR handler will return the endpoint response in the form of a Promise (such as axios, fetch).
* The response object will look like the following: {data: "A0B3HCJ"}
* The containing element ref isn't used, but should remain within the class.
* Please identify, correct and comment on any errors or bad practices you see in the React component class below.
* Additionally, please feel free to change the code style as you see fit.
* Please note - React version for this exercise is 15.5.4
*/
import React, { Component } from 'react';
import queryAPI from 'queryAPI';
import PropTypes from 'prop-types'
class ShowResultsFromAPI extends Component() {
constructor(props) {
super(props);
this.container = null;
this.state = {
data: null,
error: false
}
this.onDisableDelay = this.onDisableDelay.bind(this);
this.click = this.click.bind(this)
}
onDisableDelay() {
this.props.apiQueryDelay = 0;
}
click() {
if (this.props.apiQueryDelay) {
setTimeout(function() {
this.fetchData();
}, this.props.apiQueryDelay);
}
}
fetchData() {
queryAPI()
.then(function(response) {
if (response.data) {
this.setState({
data: response.data,
error: false
});
}
});
}
render() {
return (
<>
<div class="content-container" ref="container">
{
!error ?
<p>Sorry - there was an error with your request.</p> :
<p>data</p>
}
</div>
<Button onClick={this.onDisableDelay}>Disable request delay</Button>
<Button onClick={this.click}>Request data from endpoint</Button>
</>
)
}
}
ShowResultsFromAPI.displayName = {
name: "ShowResultsFromAPI"
};
ShowResultsFromAPI.defaultProps = {
apiQueryDelay: 0
};
ShowResultsFromAPI.propTypes = {
apiQueryDelay: PropTypes.number
};
export default ShowResultsFromAPI
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment