Created
December 5, 2018 21:30
-
-
Save kmikulski/e15e59691b7b89ca6c230b64e8e22913 to your computer and use it in GitHub Desktop.
the description for this gist
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
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