Skip to content

Commit

Permalink
lib: Fix race condition in "double dialog" error check
Browse files Browse the repository at this point in the history
useState() setters are async. c-podman and navigator call
`Dialogs.close(); Dialogs.show(...)` in direct succession. In that case,
Dialogs.show() does not yet see the updated `null` value for `dialog`
and logs the error, which fails the test.

To avoid that, use a ref for "is the dialog open", which is synchronous.
  • Loading branch information
martinpitt committed Nov 16, 2023
1 parent 9da9229 commit 140b7e6
Showing 1 changed file with 8 additions and 3 deletions.
11 changes: 8 additions & 3 deletions pkg/lib/dialogs.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -97,24 +97,29 @@
* Same as "Dialogs.show(null)".
*/

import React, { useState, useContext } from "react";
import React, { useContext, useRef, useState } from "react";

export const DialogsContext = React.createContext();
export const useDialogs = () => useContext(DialogsContext);

export const WithDialogs = ({ children }) => {
const is_open = useRef(false); // synchronous
const [dialog, setDialog] = useState(null);

const Dialogs = {
show: component => {
if (component && dialog !== null)
if (component && is_open.current)
console.error("Dialogs.show() called for",
JSON.stringify(component),
"while a dialog is already open:",
JSON.stringify(dialog));
is_open.current = !!component;
setDialog(component);
},
close: () => setDialog(null),
close: () => {
is_open.current = false;
setDialog(null);
},
isActive: () => dialog !== null
};

Expand Down

0 comments on commit 140b7e6

Please sign in to comment.