Skip to content

useAction

Wraps a ROS 2 action client (roslib.Action). Tracks the lifecycle of a single in-flight goal at a time — call sendGoal again to replace it.

tsx
import { useAction } from "roshooks";

interface FibonacciGoal {
  order: number;
}
interface FibonacciFeedback {
  sequence: number[];
}
interface FibonacciResult {
  sequence: number[];
}

const { sendGoal, cancelGoal, state, feedback, result, error } = useAction<
  FibonacciGoal,
  FibonacciFeedback,
  FibonacciResult
>({
  name: "/fibonacci",
  actionType: "example_interfaces/Fibonacci",
});

Options

OptionTypeDescription
namestringThe action name, e.g. "/fibonacci".
actionTypestringThe action type, e.g. "example_interfaces/Fibonacci".

Returns

FieldTypeDescription
sendGoal(goal: TGoal) => voidSends a new goal, replacing any goal state tracked from a previous call.
cancelGoal() => voidCancels the goal currently in flight, if any.
stateActionStateSee below.
feedbackTFeedback | nullThe most recent feedback message.
resultTResult | nullThe result, once the goal has succeeded.
errorstring | nullThe failure message, if the goal failed.
actionAction<TGoal, TFeedback, TResult> | nullThe underlying roslib.js Action client, or null before it's created.

ActionState

ts
type ActionState = "idle" | "sending" | "active" | "succeeded" | "failed" | "canceled";
idle → sending → active → succeeded
                     │  └───────────→ failed
                     └─────────────→ canceled
  • idle — no goal has been sent yet (or the action's name/actionType just changed).
  • sendingsendGoal was just called; no feedback has arrived yet.
  • active — at least one feedback message has been received.
  • succeeded / failed / canceled — terminal states.

Example

tsx
function FibonacciDemo() {
  const { sendGoal, cancelGoal, state, feedback, result } = useAction<
    FibonacciGoal,
    FibonacciFeedback,
    FibonacciResult
  >({
    name: "/fibonacci",
    actionType: "example_interfaces/Fibonacci",
  });

  return (
    <div>
      <button onClick={() => sendGoal({ order: 10 })}>Send goal</button>
      <button onClick={cancelGoal} disabled={state !== "active" && state !== "sending"}>
        Cancel
      </button>
      <p>state: {state}</p>
      {feedback && <p>feedback: {feedback.sequence.join(", ")}</p>}
      {result && <p>result: {result.sequence.join(", ")}</p>}
    </div>
  );
}

WARNING

This Hook targets ROS 2's simplified Action API. If you're on ROS 1 with actionlib, use roslib.js's ActionClient / Goal classes directly via useRos.

Released under the BSD-3 License.