r/reactjs • u/ZwickysLeap • Feb 21 '24
Needs Help Updating a time series plot with new data
I have a websocket that provides data in the form of
{time: 123, amp: 1, angle: 30}
In my App I have that
const [chartData, setChartData] = React.useState(null)
my websocket uses setChartData(response)
and chartData is passed as a prop to a Plot component
I am able to plot this data, but everytime I get new data from the websocket, it overwrites my previous values.
In my Plot component I have:
const [chartData, setChartData] = React.useState(null)
which is set if the prop data from the websocket is not null.
How can I keep the previous data points and just add the new ones to the end?
1
u/ZwickysLeap Feb 21 '24
What is the correct way to go about this?
1
u/andyer92 Feb 21 '24
What if
chartDatawas updated to be an array?const [chartData, setChartData] = React.useState<{time: number, amp: number, angle: number}[]>([])Then when you call
setChartData, you could append the response object to prev statesetChartData(prevState => [...prevState, response])