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

What is the best way to send parameters to a callback function in a jQuery $.getJSON method?

Currently, I am attempting to utilize jQuery to access a custom API using Ajax/$.getJSON. In my code, I am trying to send a specific value to the Ajax callback method, but I am encountering an issue where this value is not being properly passed and instea ...

Steps for inserting new text in front of an element's existing text

Is there a way to insert text before the original content of an element? I know how to add text after using createTextNode, as shown in this example: $("#button").click(function() { $( ".text" ).append( document.createTextNode( " Hello" ) ); }); < ...

Transforming JavaScript to TypeScript in Angular: encountering error TS2683 stating that 'this' is implicitly of type 'any' due to lacking type annotation

While in the process of migrating my website to Angular, I encountered an error when attempting to compile the JS into TS for my navbar. After searching around, I found similar issues reported by other users, but their situations were not quite the same. ...

Lunar - incorporate route parameter into DOM query_operation

Is there a way to take a route parameter and use it to trigger a click event on a DOM element? The issue is that onBeforeAction is called before the DOM is fully loaded. Any suggestions on how to solve this problem? JS onBeforeAction: function(){ var ...

Making a Jquery Ajax Request in Real Time

Is there a way to make sure that the "Test Data" text is only displayed in the console after the book details are fully loaded into vm.books? I am trying to make a synchronous ajax call for this purpose. The code below is not producing the expected result ...

Conceal a div until reaching the end of the webpage by scrolling

Currently, I am working on a web page inspired by music release pages (check out an example here). My goal is to have certain hidden divs at the bottom of the page only reveal themselves once the user has scrolled all the way down, with a delay of a few se ...

Removing one element from an array with mongoose

As a newcomer to web development, I am currently working on creating a todo app. Below is the schema and model that I have: const tdSchema = new mongoose.Schema({ category: { type: String, required: true, unique: true }, tds: { type: ...

Enable swipe functionality for mobile users

Looking to make the code below swipable on mobile devices. Any suggestions or resources to achieve this would be greatly appreciated! <script> var links = document.querySelectorAll(".heart"); var wrapper = document.querySelector("# ...

Disable the button until all input fields contain text in ASP

Curious if anyone knows how to disable a button until all text boxes have input in ASP.NET and C#. Here is an image showing the scenario I'm referring to - wanting to gray out the commit button. Thanks, Chris! ...

Error: The term "Image" is unrecognizable

I'm in the process of creating a website where I want to display images via links. If the image is missing or only 1 pixel wide, I need the site to show an alternative image. My technology stack includes Jade/Pug and JS. Before rendering the links on ...

The function req.checkBody does not exist

Currently, I am following the guidance of the Mozilla Express tutorial (https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/forms). However, as I reached the section involving express-validator, I encountered a persistent error messag ...

Identification of inappropriate language in usernames

One of the challenges I'm facing is detecting inappropriate language in usernames. Currently, I am using regex to validate the username based on a specific pattern: "/^[A-Za-z0-9]*(\d*\.\d*)*[A-Za-z0-9]+$/" This regex pattern allows u ...

Error: Property 'config' cannot be accessed because it is null

Upon transferring my Angular project from my local computer to a Linux server, I attempted to launch the project using ng serve but encountered an issue where it opened a new file in the console editor instead. After some investigation, I tried running np ...

Utilizing AngularJS filter method to populate data

Just beginning my journey with Angular js, I've got this snippet of code that is responsible for binding data to the div element, app.filter("myfilter", function () { return function (data, catName) { if (angular.isArray(data) && angular ...

Implementing $modal.open functionality in AngularJS controller using Ui-Bootstrap 0.10.0

Is there a way to properly call $modal.open from the controller in AngularJS since the removal of the dialog feature in ui-bootstrap 0.1.0? What is the alternative method available in the current version? In previous versions like 0.1.0, it was simply don ...

Handling multiple promises with JavaScript/Express Promise.all()

For my latest project, I am developing a movie discussion forum where users can create profiles and list their favorite films. To display the details of these movies, I have integrated the OMDB API with a backend route built using Express. In my initial t ...

Show specific content based on which button is selected in HTML

I am working on a project where I have three buttons in HTML - orders, products, and supplier. The goal is to display different content based on which button the user clicks: orders, products, or supplier information. function showData(parameter){ i ...

Time value given is not valid - date-fns error

Currently I am following the Next.js tutorial and encountering issues with the date.js file. import { parseISO, format } from 'date-fns' export default function Date({ dateString }) { const date = parseISO(dateString) return <time dateTim ...

Can you explain the term used to describe when specific sections of the source code are run during the build process to improve optimization?

One interesting feature I've noticed in next.js is its automatic code optimization during the build process. This means that instead of running the code every time the app is executed, it's evaluated and executed only once during the build. For ...

Search through an array of objects that contains nested arrays of objects with various property names and values

I have an Array of objects structured like this: [{ property1: 'test', property2: 'test', filter: [{ fil1: 1, fil2: 2, fil3: 3 }, { fil1: 56, fil2: 3, fil3: 34 ...