[TS] Need Help with useActionState
Answered
alfon posted this in #help-forum
alfonOP
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.
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.
15 Replies
alfonOP
Server Action
Client
This is what I have right now. Its a bit unintuitive but perhaps someone have a better Typescript Setup?
"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?
Giant panda
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.
alfonOP
It gives an error if it's not type. Type inference sucks with useActionState :(
Giant panda
useActionState will deduce the types from usage.
@alfon It gives an error if it's not type. Type inference sucks with useActionState :(
Giant panda
That's incorrect.
alfonOP
Giant panda
Answer
alfonOP
thats why im wondering on how do you set it up correctly
WELL
Giant panda
The state can't be undefined.
alfonOP
switching
undefined to unknown works HAHAthats 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!