I have a component that queries data from an API and displays a chart, however, toggling the line components on and off triggers another API call due to the toggle states being useEffect paramaters.
Component:
const Chart = (props) => { const [timeRange, setTimeRange] = useState({range: '1d', interval: '5m', long: '1 day'}) const [chartData, setChartData] = useState({}); const [chartIsLoading, setChartIsLoading] = useState(true); const [chartHasError, setChartHasError] = useState(false); const [displayLinearRegressionLine, setDisplayLinearRegressionLine] = useState(false); const [displaySMALine, setDisplaySMALine] = useState(false); const handleTimeRangeSelect = (event, newTimeRange) => { setTimeRange(newTimeRange) }; useEffect(() => { getChartData(ticker, timeRange) .then(response => { setChartData(formatResponseForRechart(response)) setChartIsLoading(false); }) .catch((error) => { console.log(error) setChartHasError(true); }); }, [ticker, timeRange, displayLinearRegressionLine, displaySMALine]) return ( <Container disableGutters maxWidth="med" className={classes.chartContainer}> <ResponsiveContainer width="98%" height={320}> <LineChart data={chartData.rechartData} axisLine={false} > {displayLinearRegressionLine && <Line stroke="blue" data={chartData.linearRegressionValues} type="monotone" dataKey="lrValue" dot={false} />} {displaySMALine && <Line stroke="pink" data={chartData.SMAvalues} type="monotone" dataKey="runningAveragePrice" dot={false} />} </LineChart> </ResponsiveContainer> <ToggleButton value="check" displayLinearRegressionLine={displayLinearRegressionLine} onChange={() => { setDisplayLinearRegressionLine(!displayLinearRegressionLine); }} > Display Linear Regression Line </ToggleButton> <ToggleButton value="check" displayLinearRegressionLine={displayLinearRegressionLine} onChange={() => { setDisplaySMALine(!displaySMALine); }} > Display Simple Moving Average Line </ToggleButton> </Container> ); } export default Chart;
Is there a way to toggle the lines without firing off another API call? (Some of the code is not displayed to get rid of code not pertinent to the question)
https://stackoverflow.com/questions/65545998/how-can-i-toggle-a-rechart-line-without-re-rendering-the-whole-component January 03, 2021 at 10:04AM
没有评论:
发表评论