#[TS] Need Help with useActionState

1 messages · Page 1 of 1 (latest)

velvet flax
#

How do you type your useActionState server actions?

If anyone have basic TS example snippet of using useActionState, that would be appreciated.

I seem to have difficulties in getting the right type of useActionState that I like to use useTransition more than useActionState.

spice wingBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

velvet flax
#

Server Action

"use server"

import { getRobots } from "@/app/lib/get-robots"
import { parseError } from "@/app/module/error/ErrorCard"

export async function getRobotsAction(state: undefined, payload: string) {
  try {
    const robots = await getRobots(payload)
    return { data: robots }
  } catch (e) {
    const error = parseError(e)
    return { error }
  }
}

export type GetRobotsActionPayload = string
export type GetRobotsActionState = Awaited<ReturnType<typeof getRobotsAction>> | undefined
export type GetRobotsAction = (state: GetRobotsActionState, payload: GetRobotsActionPayload) => Promise<GetRobotsActionState> 

Client

  const [state, dispatch, pending] = useActionState<
    GetRobotsActionState,
    GetRobotsActionPayload
  >(getRobotsAction as GetRobotsAction, undefined)

This is what I have right now. Its a bit unintuitive but perhaps someone have a better Typescript Setup?

fervent schooner
#

Why do you want to type it in the first place?

#

The only thing that might be worth typing is the state and that's it.

velvet flax
#

It gives an error if it's not type. Type inference sucks with useActionState :(

fervent schooner
#

useActionState will deduce the types from usage.

velvet flax
fervent schooner
velvet flax
#

thats why im wondering on how do you set it up correctly

#

WELL

fervent schooner
#

The state can't be undefined.

velvet flax
#

switching undefined to unknown works HAHA

#

thats the correct type im looking for

#
export async function getRobotsAction(
  state: unknown,  
  // This needs to be `unknown` if you don't need previous state
  // and it can't be undefined
  payload: string
) { ... }
#

Thanks!