guys hope everyine is doing well. So I am new to React and attempting to create a Stock APP. This component fetches the stock data for a stock I select from my Stocklist( another component) . I'm using a custom hook and it's functioning properly, but I am getting the cannot read property 'map' of undefined . The Json I am expecting has two arrays , detailed and aggregated and each array contains objects with a date property and a price property. I am attempting to map that data so that I can produce it into a graph.
The problem is the map function is executing before I select this activeStock, so it's trying to map a property of null, even though I put it in a conditional statement so it shouldn't execute
import React from 'react';
import Highcharts from 'highcharts'
import HighchartsReact from 'highcharts-react-official'
import useFetch, { DEFAULT_OPTIONS } from '../shared/useFetch';
const StockGraph = (props) => {
const activeStock = props.activeStock
const string = "stocks/"
const activeURL = string.concat(activeStock, "/price/today")
console.log(activeURL)
const [stocks, isLoading, error] = useFetch(activeURL, DEFAULT_OPTIONS);
if (error) {
return <div>`Error: {error}`</div>;
} else if (isLoading) {
return <div>Loading...</div>;
} else if (stocks != null ) {
const stockdetails= stocks.detailed
const detailed = stockdetails.map((item) => {
return {
x: new Date(item.date),
y: item.price
};
});
const stocksaggr= stocks.aggregated
const aggregated = stocks.aggregated.map((item) => {
return {
x: new Date(item.date),
y: item.price
};
});
const options = {
chart: {
type: 'line'
},
title: {
text: activeStock
},
subtitle: {
text: ''
},
xAxis: { type: 'datetime' },
plotOptions: {
line: {
dataLabels: {
enabled: false
},
enableMouseTracking: false
}
},
series: [
{
name: 'detailed',
data: detailed
}
,
{
name: 'aggregated',
data: aggregated
}
]
};
console.log('graph-render', stocks)
return (
<section className='stock-graph'>
<div id="stockGraphContainer" className="stock-graph__container">
<HighchartsReact
highcharts={Highcharts}
options={options}
/>
</div>
</section>
)
}
else {
return null;
}
}
export default StockGraph;