diff --git a/packages/graphiql-react/src/components/toolbar-button/index.tsx b/packages/graphiql-react/src/components/toolbar-button/index.tsx index 0238d256627..8970a88fa2f 100644 --- a/packages/graphiql-react/src/components/toolbar-button/index.tsx +++ b/packages/graphiql-react/src/components/toolbar-button/index.tsx @@ -11,16 +11,17 @@ import './index.css'; interface ToolbarButtonProps extends ComponentPropsWithoutRef<'button'> { label: string; + onClick?: (args?: any) => any | Promise; } export const ToolbarButton = forwardRef( ({ label, onClick, ...props }, ref) => { const [error, setError] = useState(null); - const handleClick: MouseEventHandler = event => { + const handleClick: MouseEventHandler = async event => { try { // Optional chaining inside try-catch isn't supported yet by react-compiler if (onClick) { - onClick(event); + await onClick(event); } setError(null); } catch (err) { diff --git a/packages/graphiql-react/src/stores/editor.ts b/packages/graphiql-react/src/stores/editor.ts index 3d9c03dbd98..2c51384c947 100644 --- a/packages/graphiql-react/src/stores/editor.ts +++ b/packages/graphiql-react/src/stores/editor.ts @@ -478,6 +478,8 @@ export const createEditorSlice: CreateEditorSlice = initial => (set, get) => { const { queryEditor, headerEditor, variableEditor, onPrettifyQuery } = get(); + const errors: any[] = []; + if (variableEditor) { try { const content = variableEditor.getValue(); @@ -491,6 +493,7 @@ export const createEditorSlice: CreateEditorSlice = initial => (set, get) => { 'Parsing variables JSON failed, skip prettification.', error, ); + errors.push(error); } } @@ -507,21 +510,32 @@ export const createEditorSlice: CreateEditorSlice = initial => (set, get) => { 'Parsing headers JSON failed, skip prettification.', error, ); + errors.push(error); } } - if (!queryEditor) { - return; + if (queryEditor) { + try { + const content = queryEditor.getValue(); + const formatted = await onPrettifyQuery(content); + if (formatted !== content) { + queryEditor.setValue(formatted); + } + } catch (error) { + // eslint-disable-next-line no-console + console.warn('Parsing query failed, skip prettification.', error); + errors.push(error); + } } - try { - const content = queryEditor.getValue(); - const formatted = await onPrettifyQuery(content); - if (formatted !== content) { - queryEditor.setValue(formatted); + + if (errors.length) { + if (errors.length > 1) { + const msg = errors + .map(err => err?.message || 'Error prettifying') + .join(', '); + throw new Error(msg); } - } catch (error) { - // eslint-disable-next-line no-console - console.warn('Parsing query failed, skip prettification.', error); + throw errors[0]; } }, mergeQuery() {