Actions
/ API Reference
Actions
/ API Reference

useAction

A convenience hook for working with server actions in React (new tab).

The Gist

Note

This examples uses Next.js (new tab), but this also works with any other framework supporting server actions.

import { useAction } from '@weser/actions'
import { useRouter } from 'next/navigation'

// async server action that returns a promise with 'use server' directive
// createItem takes an object with just a name property
import createItem from '@/actions/createItem'

function Component() {
  const router = useRouter()
  const [{ loading }, execute] = useAction(createItem, {
    onSuccess: (data) => {
      if (data?.id) {
        router.push('/items/' + data.id)
      }
    },
    onError: () => alert('Something went wrong'),
  })

  return (
    <button
      disabled={loading}
      onClick={() =>
        execute({
          name: 'My Item',
        })
      }>
      {loading ? 'Creating...' : 'Create Item'}
    </button>
  )
}

Parameters

ParameterTypeDescription
action(payload: P) => Promise<T_ActionResponse<T>>The action to execute.
callbacksCallbacks?The callbacks for the action.

Callbacks

ParameterTypeDescription
onSuccess(data: T) => void?The function to call when the action succeeds.
onError(error: string) => void?The function to call when the action fails.

Returns

([State<T>, (payload: P) => Promise<void>]) A tuple where the first element is the state of the action and the second element is the function to execute the action.

State

ParameterTypeDescription
loadingbooleanWhether the action is loading.
dataT | nullThe data returned from the action.
errorstring | nullThe error returned from the action.
On this page