Build a Stock Market App with React
Tags: react, stockmarket, api, javascript
Published: 2021-03-06 11:11:17

Stock Market API and ReactJS together? <3

This is a very basic application to the world of REST APIs. I strongly feel you will get the basic hang of using REST APIs after going through this blog. 

I'm using codesandbox.io for building this app.

Here's a peek into the final output of this application:
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z9rivlb0vh3qmdmr9pcx.gif)

Aight! Let's get into cooooddiiinngg. 


## Visualization 

Let us first visualize what we are going to build exactly?
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w4kin87tbm92w78flber.png)


## Setting up the JSX

```html
        <header>
          <h2>Stock Calculator</h2>
        </header>
```
Hurray! Our header is set. Ok, let me bring down my excitement and let's get our hand's dirty now.


Let us make the rest of the JSX elements now.

```html
       <input
         placeholder="Stock Name"
         onInput={(event) => setStock(event.target.value)}
        />

        <input
          placeholder="Purchased Price"
          onInput={(event) => setPurchasedPrice(event.target.value)}
        />

        <input
          placeholder="Quantity Purchased"
          onInput={(event) => setQuantityPurchased(event.target.value)}
        />
       
        <button onClick={clickHandler}
          Submit
        </button>

        <p id="output"> 
         {output}
        </p>
```
Now you'll probably land up with tons of error messages, as we didn't import { useState } and we didn't initialize the useState for the respected variables. 

So let us do that? :D

```javascript
  const [stock, setStock] = useState("");
  const [purchasedPrice, setPurchasedPrice] = useState("");
  const [quantityPurchased, setQuantityPurchased] = useState("");
  const [output, setOutput] = useState("");
```

## Integrating with the API

The API that we use for the purpose of this blog is from finnhub.io. There is no specific reason for choosing this particular API, this was the one that I found first and it was easy enough for me to integrate it! :D

**Getting the API key/Token from finnhub**
Finnhub.io --> Get Free API key --> Copy the API key

Once that is done, you can proceed to Finnhub.io --> Documentation --> Stock Price --> Quote

You can refer to the documentation, if you have any doubts. 
Anyways enough talk, let's get to coding! :)

```javascript
  const url = "https://finnhub.io/api/v1/quote?";

  function stockURL(stock) {
    let name = stock.toUpperCase();
    return url + "symbol=" + name + "&token=c07um4f48v6uu9ck9l4g";
  }

```
We defined the URL of the API, then created a function that returns to a URL with the name of the stock that we want, along with the token key.

Now let's get into the **Fetch Call**.

```javascript
// clickHandler() is the function that gets called when we press the Submit button

function clickHandler() {
    // Point 1
    fetch(stockURL(stock))
      //Point 2
      .then((response) => response.json())
      //Point 3
      .then((event) => {
        let currentPrice = event.c;
        //Point 4
        let totalPastPrice = parseInt(purchasedPrice) * parseInt(quantityPurchased);
        let totalCurrentPrice = parseInt(currentPrice) * parseInt(quantityPurchased);

        let balance = totalCurrentPrice - totalPastPrice;

        // Point 5
        if (balance > 0) {
        let percentage = (
            (parseInt(quantityPurchased) / parseInt(purchasedPrice)) *
            100
          ).toFixed(2);
          setOutput(
            `You made a profit of ${percentage} which amounts to $ ${balance} `
          );} 


       else if (balance < 0) {
          var percentage = (
            (parseInt(purchasedPrice) / parseInt(quantityPurchased)) *
            100
          ).toFixed(2);
          setOutput(
            `You made a loss of ${percentage}% which amounts to $${-balance} `
          );} 


     else setOutput("You made neither a profit nor a loss.");
      })
      
      //Point 6
      .catch((event) => alert("There is something wrong with the server"));}

```
1. The fetch calls a function stockURL, with an argument of "stock". The value of "stock" is received from the user through the input box. The stockURL function then returns a URL consisting of the name of the stock and the token key.

2. Now, we tell the fetch call to transform all the data from the returned URL into json format. 

3. From the given json format, we take the data of "c" alone as it indicated to the "current price" of the stock. You can return other values as well. (Refer documentation for other values)

4. We calculate the totalPastPrice, totalCurrentPrice based on the input received from the user (setPurchasedPrice & setQuantityPurchased has already been done when the user types in the input box). Then the balance is calculated.

5. If the balance is positive ie. the user has made a profit. We find the percentage. The parseInt is used for converting the string to a number, and toFixed(2) is used for rounding & limiting the number of decimal digits to 2.
Now the setOutput ie. Display to the output box. Similar process occurs for balance negative and zero.

6. If there's any issue with the server or the server is over-loaded, an alert box shows up to the user indicating the same.


**Hurrayyy! That's it.**

Now, you can add in the CSS and style it as you like. Maybe even add <datalist> so that the user can select the stock from the list. 

**[Click here] (https://0cz6j.csb.app/) for the link to the live demo.**

**Disclaimer:** I am a complete newbie into the web dev world, so if I haven't practiced the best-practices - do let me know & I'll be more than glad to correct myself. :D

I document my journey and experiences on [Twitter](https://twitter.com/themohammadsa) and [LinkedIn](https://www.linkedin.com/in/themohammadsa/).