summaryrefslogtreecommitdiffstats
path: root/fetch-MSFT-stockprice-API-request-react.js
blob: 1df838f2633efacdce5721312de2116245ec1228 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import React from 'react';
import logo from './logo.svg';
import './App.css';

const axios = require('axios');

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { status: 'LOADING' };
  }

  componentDidMount() {
    const symbol = this.props.symbol;
    const url = `https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=${symbol}&apikey=demo`;

    axios.get(url).
      then(res => this.setState({
        error: null,
        status: 'DONE',
        price: res.data['Global Quote']['05. price']
      })).
      catch(err => this.setState({
        error: err.message,
        status: 'ERROR',
        price: 'N/A'
      }));
  }

  render() {
    if (this.state.status === 'ERROR') {
      return (<h1>Error: {this.state.error}</h1>);
    } else if (this.state.status === 'DONE') {
      return (<h1>Price: {this.state.price}</h1>);
    } else {
      return (<h1>Loading...</h1>);
    }
  }
}

export default App;