I am currently working on developing a web application using Next.js (13.4.9) and I intend to utilize server actions. These server actions will involve sending data to the server, which will process the data and return a string back to me. The challenge I'm facing is that the only method I have found to retrieve the resulting data from the server action is through cookies. Is there an easier way for me to access the data obtained from the server action? Additionally, I would like to know how I can refresh the page or redirect the user to another page immediately after executing the server action, similar to what can be done with PHP.
Below is my current code:
// page.tsx
"use client";
import React, { useTransition, useState } from "react";
import { SendTicket } from "@/actions/TicketAction";
import Cookies from "js-cookie";
export default function TicketPage(){
const [isPending, startTransition] = useTransition();
const [ name, setName ] = useState<string>("");
const [ age, setAge ] = useState<number>(0);
return(
<main>
<form action={() => startTransition(() => SendTicket({
name: name, age: age
}))}>
<input type="text" value={name} onChange={(e) => setName(e.target.value)}
placeholder="Your name" />
<input type="number" value={age} onChange={(e) => setAge(parseInt(e.target.value))}
placeholder="Your age" />
<button type="submit">
Valider
</button>
</form>
{ isPending ? <span>Loading...</span> : <></> }
<Result />
</main>
)
}
function Result(){
const ResultString = Cookies.get("ResultString");
Cookies.remove("ResultString");
return(
<p>{ResultString?.toString()}</p>
)
}
// TicketAction.ts
"use server";
import { cookies } from "next/headers";
export interface TicketInformationProps {
name: string;
age: number;
}
export async function SendTicket(TicketInforamtion: TicketInformationProps){
console.log(`[NEW TICKET]`);
console.log(`Nom: ${TicketInforamtion.name}`);
console.log(`Age: ${TicketInforamtion.age.toString()}`);
console.log(`\n\n\n`);
const result = `You are ${TicketInforamtion.name} and you are ${TicketInforamtion.age.toString()} yo.`;
cookies().set({
name: "ResultString",
value: result,
path: "/ticket",
expires: new Date(Date.now() + 1000 * 1),
secure: true,
});
}