Is it possible to use a server action in Next.js to both retrieve data and refresh the page?

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,

    });
}

Answer №1

If you're looking to retrieve the response data, here's how you can do it:

import { experimental_useFormState as useFormState } from 'react-dom'

...

  const [state, formAction] = useFormState(action);

...

Keep in mind that the state will remain undefined (or can be initialized) until a response is received from the server action.

Answer №2

To implement in Next.js version 14:

Utilize the useFormState() hook to modify data on the server and return an object that triggers a rerender of the component after form submission (similar to a refresh).

Important: Remember to call revalidatePath('/') after updating the data to inform Next.js that the component handling the form submission is dynamic, prompting it to rerender upon new requests instead of serving a cached page version.

Answer №3

server actions are currently in their experimental phase. It is important to configure this in your next.config.js

const nextConfig = {
  experimental: {
    serverActions: true,
  },
};

The "use server" directive must be at the beginning of the component function body.

// This will trigger a refresh
import { revalidatePath } from "next/cache";

export async function SendTicket(TicketInformation: TicketInformationProps){   

    const result = `You are ${TicketInforamtion.name} and you are ${TicketInforamtion.age.toString()} yo.`;
    "use server"
    cookies().set({
        name: "ResultString",
        value: result,
        path: "/ticket",
        expires: new Date(Date.now() + 1000 * 1),
        secure: true,
    });
    revalidatePath("/route");

}

Server actions are utilized for modifying data on the server or executing server-specific tasks. It may not support returning a value for use within the component.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The data stored in LocalStorage disappears when the page is refreshed

I'm facing an issue with the getItem method in my localStorage within my React Form. I have added an onChange attribute: <div className = 'InputForm' onChange={save_data}> I have found the setItem function to save the data. Here is ...

Having issues with the input event not triggering when the value is modified using jQuery's val() or JavaScript

When a value of an input field is changed programmatically, the expected input and change events do not trigger. Here's an example scenario: var $input = $('#myinput'); $input.on('input', function() { // Perform this action w ...

AngularJS efficiently preloading json file

I am just starting to learn about angularJS. Apologies if my question is not very clear. Here is the problem I am facing: I have a JSON file that is around 20KB in size. When I attempt to load this file using the 'factory' method, I am receivin ...

Are there any factors within a local network or desktop environment that may impact the execution of JScript?

Something strange is happening with the JavaScript on my project. It works perfectly fine, except when accessed from computers at a specific company. Even more puzzling is that the JavaScript only fails about half of the time when accessed from that compan ...

Tips on gathering information from an HTML for:

After encountering countless programming obstacles, I believe that the solution to my current issue is likely a simple fix related to syntax. However, despite numerous attempts, I have been unable to resolve it thus far. I recently created a contact form ...

"Encountering an error in Next Js: module 'next

I recently set up a Next.js project and deployed it to my CPanel. I also created a server.js file within the directory. However, when trying to access my website, I encountered an error message. The error displayed was: internal/modules/cjs/loader.js:638 ...

choose multiple elements from an array simultaneously

Looking for help with a basic Array question and seeking the most effective solution. The scenario involves having an array: var pathArr = [element1, element2, element3, element4, element5, element6] If I want to select multiple elements from this array ...

Trouble with HTTPS request in Android fragment

My app crashes and returns to the main activity whenever I try to use the search function with the Kitsu API in my fragment. I have observed through Logcat that no data is being fetched, but I am unable to determine what is causing the crash.The LogCat r ...

Creating dynamic axes and series in Ext JS 4 on the fly

I am looking to dynamically generate the Y axis based on a JSON response. For example: { "totalCount":"4", "data":[ {"asOfDate":"12-JAN-14","eventA":"575","eventB":"16","eventC":"13",...}, {"asOfDate":"13-JAN-14","eventA":"234","eventB":"46","even ...

Unspecified property in Vue.JS data object

Whenever I try to display my modal, an error pops up indicating that the property is not defined, even though I have clearly declared it in the Data(). It seems like there is a crucial aspect missing from my understanding of how everything functions... T ...

Displaying components conditionally based on whether the user is authenticated

I am currently facing a challenge in my web application related to conditional rendering based on the user's authentication status. The Page component should display either the NotLoggedHome or LoggedHome component depending on the user's state. ...

Tips for integrating Redux toolkit with the latest version of Next.js

It seems that in order to incorporate redux into my app, I must enclose the majority of it within a redux provider, which should be a client component. As a result, almost every part of my app becomes a child of this client component. Does this imply tha ...

Implementing a codeigniter delete confirmation box with Javascript

I have tried numerous solutions on this site, but nothing seems to be working for me. I am trying to implement a pop-up window confirmation before deleting my data. Here is the code I am using: <a href="<?php echo site_url('admin/barang/delet ...

Can a Unicode character be overwritten using a specific method?

Is there a way to display a number on top of the unicode character '♤' without using images? I have over 200 ♤ symbols each with a unique number, and using images would take up too much space. The characters will need to be different sizes, a ...

What is the best method for incorporating a nonce into inline styles and scripts within Next.js?

When implementing a Content-Security-Policy with settings like: default-src 'self'; script-src https://ray.run Next.js encounters issues that prevent it from working properly, resulting in errors such as: The application of inline styles is deni ...

The time-out counter fails to detect the input field

After writing a method to reset the timeout on mouse click, keyup, and keypress events, I realized that it does not account for input fields. This means that when I am actively typing in a field, the timeout will still occur. Below is the code snippet: ...

What is the process for dynamically looping through a table and adding form data to the table?

I am in the process of developing an hour tracking website that utilizes a form and a table. Currently, I have implemented the functionality where the form content gets added to the table upon the first submission. However, I need it to allow users to inp ...

What could be causing the data to not load from the database when the page is loaded?

My current setup involves a button that triggers a specific function upon loading. return ( <> <LikeButtonStyle onLoad={getUserData} onClick={addInfo}> <Image width="10px" height="auto" src="/ ...

Ways to effectively utilize jQuery objects as arguments in the delegate function

When working with delegate and multiple selectors, you can use the following syntax: $(contextElement).delegate('selector1, selector2' , 'eventName', function(){ //blabla }); In projects where managing DOM elements is important, stori ...

Steps to create a submit button that is linked to a URL and includes an image

I'm attempting to convert my submit button into an image that, when clicked, redirects to another page. Currently, the submit button is functional but lacks the desired image and href functionality. <input type="submit" name="submit" alt="add" o ...