Reputation: 15
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;
Upvotes: 0
Views: 176
Reputation: 21
Like what others said, your conditional is only checking if stocks
is null. stocks.detailed
or stocks.aggregated
is what is being mapped so check if those values even exist. Double check if your useFetch()
hook is really working as expected and getting the values you need. Throw logs at key points and you'll get closer to pinpointing what is going on.
Upvotes: 1
Reputation:
Sounds like stocks.detailed
or stocks.aggregated
itself is undefined
. You need to add either add another conditional statement to check for that before executing the map
. Or, maybe it shows another underlying problem with your code - should stocks.aggregated
/detailed
be defined at that point? If so, why isn't it? I can't tell you from what information you've given, unfortunately.
Upvotes: 2