I fetched data from this API and I would like to store certain things into State or a variable (as an array).
var baseUrl = `https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=IBM&apikey=https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=IBM&apikey=<api_key>`;
const [chart, setChart] = useState();
useEffect(() => {
axios.get(baseUrl).then(res => {
setChart(res.data);
console.log(res.data);
});
}, [baseUrl]);
useEffect(()=>{}, [chart]);
At this point, chart (state) has all the data stored ( 100 entries ).
"Meta Data": {
"1. Information": "Daily Prices (open, high, low, close) and Volumes",
"2. Symbol": "IBM",
"3. Last Refreshed": "2022-05-06",
"4. Output Size": "Compact",
"5. Time Zone": "US/Eastern"
},
"Time Series (Daily)": {
"2022-05-06": {
"1. open": "135.4700",
"2. high": "137.9900",
"3. low": "135.4700",
"4. close": "137.6700",
"5. volume": "7306396"
},
"2022-05-05": {
"1. open": "136.4600",
"2. high": "137.2600",
"3. low": "134.7600",
"4. close": "135.9200",
"5. volume": "5957434"
},
Next, I would like to access "Time Series (Daily)" and get the "1. open" number for each day.
I tried to manually access that data like so ( just to see if it's working )
const getNumber = Object.keys(chart['Time Series (Daily)']["2022-05-06"]["1. open"]);
console.log("today's 1.open number is: " + getNumber);
but no.. react is very angry at me giving me an error saying: "TypeError: Cannot read properties of undefined (reading 'Time Series (Daily)')"
I also tried without Object.keys but it's giving me the same error unfortunately. What's the problem ? How can I access that data and store it into state/let/const.
Actually you don't need Object.keys. And the error you are getting is because you are calling chart before you assign it by calling setChart.
You should check if chart is not undefined, and it's better to check all properties you are accessing.
In that case for the first render you will get undefined (because you don't get data from the API yet) and then you will get the correct result.
const getNumber = chart?.['Time Series (Daily)']?.["2022-05-06"]?.["1. open"]