Skip to content

Instantly share code, notes, and snippets.

@kmikulski
Created December 5, 2018 21:30
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 kmikulski/e15e59691b7b89ca6c230b64e8e22913 to your computer and use it in GitHub Desktop.
Save kmikulski/e15e59691b7b89ca6c230b64e8e22913 to your computer and use it in GitHub Desktop.
the description for this gist
import React, { Component } from 'react';
class APIResponse extends Component {
render() {
if(this.props.response)
return ( <pre>{this.props.response}</pre> );
else
return (<div/>);
}
}
class QueryAPI extends Component {
constructor(props) {
super(props);
this.state = { response: null };
}
authorizationHeader() {
if(!this.props.keycloak) return {};
return {
headers: {
"Authorization": "Bearer " + this.props.keycloak.token
}
};
}
handleClick = () => {
fetch('http://localhost:9000/users', this.authorizationHeader())
.then(response => {
if (response.status === 200)
return response.json();
else
return { status: response.status, message: response.statusText }
})
.then(json => this.setState((state, props) => ({
response: JSON.stringify(json, null, 2)
})))
.catch(err => {
this.setState((state, props) => ({ response: err.toString() }))
})
}
render() {
return (
<div className="QueryAPI">
<button onClick={this.handleClick}>Send API request</button>
<APIResponse response={this.state.response}/>
</div>
);
}
}
export default QueryAPI;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment