0

I'm newer to React and Axios, but I'm currently working on a personal project where I use a stock market API to get the current price of a stock after hitting submit on the form. When I make an api call, both of my hooks price and total do not get updated prior to rendering the data on the page. I'm unsure why this is happening because inside of my callback function in the .then block I update both the price and total hooks based off of the responses from the API.

Ultimately when I try to add another stock to my table, it uses the previous price and total that should have been calculated for the stock prior. I appreciate any help or explanation on why this happens.

import React, { Component, useState, useEffect } from 'react';
import axios from 'axios';

function StockData(props) {
  const [ticker, setTicker] = useState();
  const [quantity, setQuantity] = useState(0);
  const [price, setPrice] = useState(0);
  const [total, setTotal] = useState(0);
  const [data, updateData] = useState([]);

  // handles form on click function to add another stock to the portfolio
  const HandleSubmit = (e) => {
    e.preventDefault();

    const stockData =
      'https://api.polygon.io/v2/aggs/ticker/' +
      ticker +
      '/prev?adjusted=true&apiKey=SuaIlAqCImCfcixB2Qn3FBuZP1mkqkfl';

    // makes get request call to polygon.io api to get stock data
    // console.log('axios request');
    axios
      .get(stockData)
      .then((response) => {
        // represents the stock ticker
        console.log(response.data.results[0]['T']);

        // this represents the stock closing price
        setPrice(response.data.results[0]['c']);

        // calculate the total of purchasing price*quantity
        let currTotal = price * quantity;
        setTotal(currTotal);

        let stock = [ticker, quantity, price, total];
        updateData([...data, stock]);
        // console.log(ticker, quantity, price, total);
      })
      .catch((error) => {
        console.log(error);
      });
    console.log(data);
  };

 return (
    <div>
      <form>
        <label>Add a Stock: </label>
        <input
          type='text'
          placeholder='Enter a Stock Ticker'
          name='ticker'
          value={ticker}
          onChange={(e) => setTicker(e.target.value.toUpperCase())}
        />
        <input
          type='number'
          placeholder='Quantity'
          name='quantity'
          value={quantity}
          onChange={(e) => setQuantity(e.target.value)}
        />
        <input type='submit' onClick={HandleSubmit}></input>
      </form>
      <div className='stock-list'>
        <table>
          <thead>
            <tr>
              <th>Ticker</th>
              <th>Quantity</th>
              <th>Price</th>
              <th>Total</th>
            </tr>
          </thead>
          <tbody>
            {data.map((stock) => (
              <tr>
                <td>{stock[0]}</td>
                <td>{stock[1]}</td>
                <td>{stock[2]}</td>
                <td>{stock[3]}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
export default StockData;

Terry
  • 23
  • 5

1 Answers1

0

I can't comment, I just arrive on StackO, so I use response to talk with you about your trouble. Do you try to put every setState on chaining.then like that :

.then(res => setState(res))
.then(res => setState2(res))
...

Say me

LutherW
  • 359
  • 2
  • 6