Skip to content

Commit

Permalink
Add onAction property in AutoButton
Browse files Browse the repository at this point in the history
  • Loading branch information
alanko0511 committed Dec 16, 2024
1 parent 7e28abc commit dc6e940
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 2 deletions.
41 changes: 41 additions & 0 deletions packages/react/cypress/component/auto/AutoButton.cy.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -183,4 +183,45 @@ describeForEachAutoAdapter("AutoButton", ({ name, adapter: { AutoButton }, wrapp

cy.contains("Flip all succeeded.");
});

it("runs the onAction callback when the button is clicked, then runs the action as normal", () => {
let onActionCalled = false;
cy.mountWithWrapper(
<AutoButton
action={api.widget.create}
variables={{ widget: { name: "foobar" } }}
onAction={() => {
onActionCalled = true;
}}
/>,
wrapper
);
cy.contains("Create Widget");

cy.intercept("POST", `${api.connection.options.endpoint}?operation=createWidget`, {
body: {
data: {
widget: {
__typename: "Widget",
id: "123",
},
},
},
}).as("createWidget");

cy.get("button")
.click()
.then(() => {
expect(onActionCalled).to.be.true;
});

cy.wait("@createWidget");
cy.get("@createWidget")
.its("request.body.variables")
.should("deep.equal", {
widget: { name: "foobar" },
});

cy.contains("Create Widget succeeded.");
});
});
10 changes: 8 additions & 2 deletions packages/react/src/auto/hooks/useAutoButtonController.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ export type AutoButtonProps<
action: ActionFunc;
/** The variables to pass to the action when run */
variables?: ActionFunc["variablesType"];
/**
* Callback function to run when the button is clicked. The action will run after this is called.
*/
onAction?: () => void;
/**
* Callback function to run when the button succeeded at running the action
* Overrides the default behavior of rendering a message to the user to display success
Expand All @@ -34,7 +38,7 @@ export const useAutoButtonController = <
>(
props: AutoButtonProps<GivenOptions, SchemaT, ActionFunc>
) => {
const { action, variables, onSuccess, onError, ...buttonProps } = props;
const { action, variables, onAction, onSuccess, onError, ...buttonProps } = props;
const { metadata, fetching: fetchingMetadata, error: metadataError } = useActionMetadata(action);

const [{ data: result, fetching: fetchingActionResult, error }, runAction] =
Expand All @@ -55,13 +59,15 @@ export const useAutoButtonController = <
}

const run = useCallback(async () => {
onAction?.();

const result = await runAction(variables);
if (result.error) {
onError?.(result.error, result);
} else {
onSuccess?.(result);
}
}, [runAction, variables, onSuccess, onError]) as () => void;
}, [onAction, runAction, variables, onError, onSuccess]) as () => void;

return {
result,
Expand Down

0 comments on commit dc6e940

Please sign in to comment.