Skip to content

Commit

Permalink
Fix race condition by using ref instead of state variable for line da…
Browse files Browse the repository at this point in the history
…ta (#177)
  • Loading branch information
PeterC-DLS authored Oct 14, 2024
1 parent 84f9803 commit 95b2b09
Showing 1 changed file with 16 additions and 16 deletions.
32 changes: 16 additions & 16 deletions client/component/src/ConnectedPlot.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,7 @@ function ConnectedPlot({
uuid,
}: ConnectedPlotProps) {
const [plotProps, setPlotProps] = useState<AnyPlotProps | null>();
const [lineData, setLineData] = useState<LineData[]>([]);
const lineDataRef = useRef<LineData[]>([]);
const [linePlotConfig, setLinePlotConfig] =
useState<PlotConfig>(defaultPlotConfig);
const [scatterData, setScatterData] = useState<ScatterData>();
Expand Down Expand Up @@ -347,7 +347,7 @@ function ConnectedPlot({
};

const clearLineData = () => {
setLineData([]);
lineDataRef.current = [];
setLinePlotConfig(defaultPlotConfig);
setPlotProps(null);
setSelections([]);
Expand Down Expand Up @@ -431,19 +431,18 @@ function ConnectedPlot({
params: LineParams,
broadcast = true
) => {
setLineData((prevLineData) => {
console.log('Finding old line with key', key);
const old = prevLineData.findIndex((s) => s.key === key);
if (old === -1) {
console.log('Line with key', key, 'cannot be found');
return prevLineData;
} else {
const all = [...prevLineData];
console.debug('Replacing old line params with', params);
all[old] = { ...all[old], ...params };
return all;
}
});
const prevLineData = lineDataRef.current;
console.log('Finding old line with key', key);
const old = prevLineData.findIndex((s) => s.key === key);
if (old === -1) {
console.log('Line with key', key, 'cannot be found');
return prevLineData;
} else {
const all = [...prevLineData];
console.debug('Replacing old line params with', params);
all[old] = { ...all[old], ...params };
return all;
}

if (broadcast) {
sendClientMessage('client_update_line_parameters', {
Expand Down Expand Up @@ -478,7 +477,7 @@ function ConnectedPlot({
yDomain
);
const plotConfig = newPlotConfig ?? linePlotConfig;
setLineData(multilineData);
lineDataRef.current = multilineData;
setLinePlotConfig(plotConfig);
setPlotProps({
lineData: multilineData,
Expand All @@ -492,6 +491,7 @@ function ConnectedPlot({
const appendMultilineData = (message: AppendLineDataMessage) => {
const newPointsData = message.alData.map((l) => createLineData(l));
console.log('%s: appending line data', plotId, Object.keys(newPointsData));
const lineData = lineDataRef.current;
const l = Math.max(lineData.length, newPointsData.length);
const newLineData: LineData[] = [];
for (let i = 0; i < l; i++) {
Expand Down

0 comments on commit 95b2b09

Please sign in to comment.