Skip to content

Instantly share code, notes, and snippets.

@kmikulski kmikulski/post.jsx
Created Dec 5, 2018

Embed
What would you like to do?
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
You can’t perform that action at this time.