alepha@docs:~/docs/reference/react-hooks$
cat useAction.md
1 min read
Last commit:

#useAction

#Import

typescript
1import { useAction } from "alepha/react";

#Overview

Hook for handling async actions with automatic error handling and event emission.

By default, prevents concurrent executions - if an action is running and you call it again, the second call will be ignored. Use debounce option to delay execution instead.

Emits lifecycle events:

  • react:action:begin - When action starts
  • react:action:success - When action completes successfully
  • react:action:error - When action throws an error
  • react:action:end - Always emitted at the end

#Examples

Basic usage

tsx
1const action = useAction({2  handler: async (data) => {3    await api.save(data);4  }5}, []);6 7<button onClick={() => action.run(data)} disabled={action.loading}>8  Save9</button>

With debounce (search input)

tsx
1const search = useAction({2  handler: async (query: string) => {3    await api.search(query);4  },5  debounce: 300 // Wait 300ms after last call6}, []);7 8<input onChange={(e) => search.run(e.target.value)} />

Run on component mount

tsx
1const fetchData = useAction({2  handler: async () => {3    const data = await api.getData();4    return data;5  },6  runOnInit: true // Runs once when component mounts7}, []);

Run periodically (polling)

tsx
 1const pollStatus = useAction({ 2  handler: async () => { 3    const status = await api.getStatus(); 4    return status; 5  }, 6  runEvery: 5000 // Run every 5 seconds 7}, []); 8  9// Or with duration tuple10const pollStatus = useAction({11  handler: async () => {12    const status = await api.getStatus();13    return status;14  },15  runEvery: [30, 'seconds'] // Run every 30 seconds16}, []);

With AbortController

tsx
1const fetch = useAction({2  handler: async (url, { signal }) => {3    const response = await fetch(url, { signal });4    return response.json();5  }6}, []);7// Automatically cancelled on unmount or when new request starts

With error handling

tsx
 1const deleteAction = useAction({ 2  handler: async (id: string) => { 3    await api.delete(id); 4  }, 5  onError: (error) => { 6    if (error.code === 'NOT_FOUND') { 7      // Custom error handling 8    } 9  }10}, []);11 12{deleteAction.error && <div>Error: {deleteAction.error.message}</div>}

Global error handling

tsx
1// In your root app setup2alepha.events.on("react:action:error", ({ error }) => {3  toast.danger(error.message);4  Sentry.captureException(error);5});