#Giving a type to Astro.getActionResult

3 messages ยท Page 1 of 1 (latest)

fiery ice
#

I'm bit old-school and I want to type everything I can. I also can't abide red-squigglies. ๐Ÿ˜‰

So when I call this:

const actionResult = Astro.getActionResult(actions.processComment);`

I really want actionResult to be typed.

So getActionResult appears to return something like SafeResult<data, error> , but when I type things:

const actionResult: SafeResult<CommentResponse, z.ZodError>  = Astro.getActionResult(actions.processComment);

I get a red-squiggly under actionResult.

Am I trying too hard? ๐Ÿ˜‰

My action is declared as:

export const server = {
  processComment: defineAction({
    accept: 'form',
    input: commentCheckerInputParams,
    handler: async (aInput: commentCheckerInput): Promise<CommentResponse> => {
      const commentChecker = new CommentChecker();
      const commentResponse: CommentResponse = await commentChecker.checkComment(aInput);
      console.log("commentResponse: ", commentResponse);
      return commentResponse;
    },
  })
}
sand trenchBOT
#

Hi @fiery ice. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Astro's getActionResult() function returns a result of an action submission. The type of this function is (action: TAction) => ActionReturnType<TAction> | undefined as per the Astro documentation (https://docs.astro.build/en/reference/api-reference/#astrogetactionresult). This means it returns either the result of the action or undefined.

The result returned by getActionResult() is an object that contains either data or error properties. The data property contains the result of the action if it was successful, and the error property contains an error object if there was an error. If no submission has been received, getActionResult() will return undefined.

Given this, you might want to define your actionResult variable like this:

const actionResult = Astro.getActionResult(actions.processComment);

Then, you can check if actionResult is undefined or if it contains an error property to handle errors. If it doesn't, you can safely assume that it contains a data property of type CommentResponse.

if (!actionResult || actionResult.error) {
  // handle error
} else {
  const commentResponse: CommentResponse = actionResult.data;
  // use commentResponse
}

This way, you're not trying to force a type onto actionResult that doesn't match what getActionResult() actually returns, which should prevent the red squiggly line from appearing.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: