'Parse data through API with useEffect for Algolia
I need to parse stock data through YahooFinance Stocks API, using RapidAPI here how it would look like as an example response.
The error I am getting is:
Uncaught (in promise) ReferenceError: Cannot access 'data' before initialization
"results":1294 items
[100 items
0:{4 items
"exchangeCode":"NMS"
"symbol":"1"
"companyName":"1"
"industryOrCategory":"N/A"
}
1:{...}4 items
2:{4 items
"exchangeCode":"NMS"
"symbol":"AAON"
"companyName":"AAON, Inc."
"industryOrCategory":"Industrials"
}
3:{4 items
"exchangeCode":"NMS"
"symbol":"AAPL"
"companyName":"Apple Inc."
"industryOrCategory":"Technology"
}
]
useEffect(() => {
const config = {
headers: {
"x-rapidapi-host": "stock-market-data.p.rapidapi.com",
"x-rapidapi-key": APIKEY,
},
};
const fetchStocks = async () => {
const json = JSON.parse(data);
const results = Object.keys(json["results"]);
const stockInfo = results.map(
(result) =>
(result = {
result,
close: String(json["results"][result]),
})
);
const { data } = await axios.get(
"https://stock-market-data.p.rapidapi.com/market/exchange/nasdaq",
config
);
data.forEach((results) => {
results.objectID = results.length;
});
setStocks(data);
};
fetchStocks();
}, [])
Solution 1:[1]
This seems like a marshaling issue in your Javascript more than an Algolia issue. Perhaps because the await axios.get() needs to be in an async function per https://stackabuse.com/making-asynchronous-http-requests-in-javascript-with-axios/
To use the async/await syntax, we need to wrap the axios.get() function call within an async function
Curious the contents of data before and after the data.forEach() (also could that be a map?)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Chuck Meyer |
