1

I would like to display the past month data from Alpha Vantage API but I don't know how could I access it. This is kinda what I would like to get back: setPrices(data.data['Monthly Time Series']['2021-12-07']); But without hard coding the date, just dynamically get the last month. What kind of object method could I use to get it ? I would appreciate any help.

This is the data I get back:

{2021-12-07: {…}, 2021-11-30: {…}, 2021-10-29: {…}, 2021-09-30: {…}, 2021-08-31: {…}, …}
2014-04-30: {1. open: '558.7100', 2. high: '604.8300', 3. low: '502.8000', 4. close: '526.6600', 5. volume: '67171200'}
2014-05-30: {1. open: '527.1100', 2. high: '567.8400', 3. low: '503.3000', 4. close: '559.8900', 5. volume: '36527700'}
2014-06-30: {1. open: '560.7000', 2. high: '582.4500', 3. low: '538.7500', 4. close: '575.2800', 5. volume: '37898400'}

This is the code I have currently:

const Search = () => {

    const [textInput, setTextInput] = useState('');
    const [tickers, setTickers] = useState([]);
    const [prices, setPrices] = useState([]);

    const inputHandler = (e) => {
        setTextInput(e.target.value);
        
    }

        const showData = async(e) => {
            e.preventDefault();
            const url = `https://www.alphavantage.co/query?function=TIME_SERIES_MONTHLY&symbol=${textInput}&apikey=${process.env.REACT_APP_ALPHA_VANTAGE_API_KEY}`
            
    
            try {
                const data = await axios.get(url);
                
                if(data) {
                    setPrices(data.data['Monthly Time Series']);
                   
               }
               } catch(err) {
                   console.log(err)
               }
               console.log(prices);
        }
    
      
    
        return (
            <StyledSearch>
                <h1>Security Price Monitor App </h1>
                <form onSubmit={submitSearch}>
                    <input type="text" value={textInput} onChange={inputHandler} placeholder='Enter Ticker'/>
                    <button type="submit" onClick={showData}>Search</button>
                </form>
            </StyledSearch>
        )
    }
evll
  • 97
  • 3
  • 12

1 Answers1

0

You could create an array and then populate everything to it:

let newObject = data; // where 'data' is the axios response

let dateArray = [];
Object.entries(newObject['Monthly Time Series']).forEach(function (date) {
    dateArray.push(date);
});

// dateArray is now all close months as objects with nested values

let outputData = dateArray.slice(0, 29);

// You can retrieve individual months as (for example):
let oneMonth = outputData[0][1]; // etc.