How to write a React app to get Stock Market data

Here’s a basic tutorial for creating a React app that queries the Alpha Vantage API to display the last day’s stock price for a given symbol. Please note that you’ll need to sign up for a Alpha Vantage API key to access the data.

Step 1: Set Up Your React App

Create a new React app using Create React App:

npx create-react-app stock-price-app
cd stock-price-app

Step 2: Install Dependencies

Install Axios for making API requests:

npm install axios

Step 3: Get Your Alpha Vantage API Key

Sign up for a Alpha Vantage API key on the Alpha Vantage website.

Step 4: Build the App

Replace the contents of src/App.js with the following code:

import React, { useState } from "react";
import axios from "axios";

function App() {
  const [symbol, setSymbol] = useState("");
  const [stockData, setStockData] = useState(null);

  const getStockData = async () => {
    try {

      // Declare base URL separately so Axios can account for CORS.
      // See https://www.geeksforgeeks.org/reactjs-cors-options/
      const baseUrl = "https://www.alphavantage.co/query";
      const response = await axios.get(
        `${baseUrl}?function=TIME_SERIES_DAILY&symbol=${symbol}&interval=5min&apikey=913XUUE23MQ1WCJN` //,
      );

      const stockPrices = response.data["Time Series (Daily)"];
      const stockPricesKeys = Object.keys(stockPrices);
      const lastTradingDay = stockPricesKeys[stockPricesKeys.length - 1];
      const lastTradingDayQuote = stockPrices[lastTradingDay];
      setStockData(lastTradingDayQuote);
    } catch (error) {
      console.error("Error fetching stock data:", error);
    }
  };

  return (
    <div className="App">
      <h1>Stock Price App</h1>
      <p>Enter a ticker symbol to get the last day's stock price.</p>
      <input
        type="text"
        value={symbol}
        onChange={(e) => setSymbol(e.target.value)}
        placeholder="Enter Ticker Symbol"
      />
      <button onClick={getStockData}>Submit</button>

      {stockData && (
        <div>
          <h2>Stock Data for {symbol}</h2>
          <p>Open Price: {stockData["1. open"]}</p>
          <p>High Price: {stockData["2. high"]}</p>
          <p>Low Price: {stockData["3. low"]}</p>
          <p>Close Price: {stockData["4. close"]}</p>
          <p>Volume: {stockData["5. volume"]}</p>
        </div>
      )}
    </div>
  );
}

export default App;

In the above code snippet, if you place the URL directly into the Axios GET call, you’ll get a CORS error since you’re making a request to a different domain. CORS considers a request going to a different domain if it differs from the current base URL in the scheme (http vs https), actual base URL www.google.com vs www.yahoo.com, or the port. Going over the details of CORS is beyond the scope of this post, but I wanted to touch on it because I had to specifically structure my code to address CORS.

The second thing to note is that the API is not really friendly. Each of the items returned can be thought of as a dictionary where each key is a string. While this is true of all APIs, all of the APIs I’ve worked with specifically return keys in pascal or camel case where each key can be accessed using the common object member notation most of us are familiar with, and in the habit of using. (i.e.: stockData.volume as opposed to stockData[“5. volume”].) Regardless, this still represents React app that interacts with a public API to get data and display it — something that is extremely useful for those looking to build a basic web app building on tools and data that are already widely available rather than reinventing the wheel.

The last thing I want to point out is that this is purely React. I did not include any UI frameworks (I typically use Material UI). The display is not going to be very pretty (nor is it meant to be), since this is really only to serve as a demonstration of how you can utilize an open API to build a web app.

Step 5: Replace API Key

Replace 'ALPHA_VANTAGE_API_KEY' in the code with your actual Alpha Vantage API key.

Now, your React app should be ready to fetch and display stock data for the given symbol. Feel free to customize the styling and add more features based on your preferences.

Step 6: Run the App

Start your app:

npm start

Open your browser and go to http://localhost:3000. You should see your stock price app.

Learn More

Leave a Reply

Your email address will not be published. Required fields are marked *