Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 697

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 62k
Author
Asked: November 25, 20242024-11-25T01:16:08+00:00 2024-11-25T01:16:08+00:00

How to use Next.Js 14 Server Actions

  • 62k

Next.Js 14 has added a lot of cool features that make development so much easier like:

  • App Router
  • Server Actions
  • Route Handlers
  • Client and Server Components

In this article, we will be covering Server Actions.

What are Server Actions

A Server Action is simply an asynchronous function that runs on the server whenever a form is submitted. It allows you to run the code directly on the server. This way, you don't have to make a separate backend or API and don't need to send requests to the API. You can communicate with a database directly in a Server Action.

You can use it in both client and server components.

Using Server Actions

Using Server Actions in Server Components

Simply make an asynchronous function inside a server component. Add the “use server” directive inside the function (at the top). Then attach an action property to the form element.

The Server Action receives a formData object as an argument that lets you access the values of the input fields. After this, you can perform validation and store information directly in a database. No need to create an API endpoint.

// server component  export const Form = () => {   const createPost = async (formData) => {     "use server"     const title = formData.get("title")     const description = formData.get("description")      // store the post in the database directly   }    return (     <form action={createPost}>       <input type="text" name="title" />       <input type="text" name="description" />       <button type="submit">Submit</button>     </form>   ) } 
Enter fullscreen mode Exit fullscreen mode

Using Server Actions in Client Components

Since a client component is rendered on the client, you cannot create Server Actions in a client component. But what you can do is, you can create a new file and add the use server directive at the top of the file. Now any function you create inside of that file will be considered a Server Action. Then you can import those Server Actions into a client component.

"use server"  export const createPost = async (formData) => {   const title = formData.get("title")   const description = formData.get("description")    // store the post in the database directly } 
Enter fullscreen mode Exit fullscreen mode

Now you can import this Server Action in a client component.

// client component "use client"  import { createPost } from './actions'  export const Form = () => {   return (     <form action={createPost}>       <input type="text" name="title" />       <input type="text" name="description" />       <button type="submit">Submit</button>     </form>   ) } 
Enter fullscreen mode Exit fullscreen mode

Showing a Loading State

Now you might be wondering, how can we show a loading state because the function is being executed on the server.

To do this you can create a separate client component for your button. Inside of this component, you can use the useFormStatus hook. It tells you whether the Server Action has finished executing or is still being executed.

Note: You can only use the useFormStatus hook inside of a form. That's why you have to create a separate component for your button and place it inside the form.

"use client"  import { useFormStatus } from "react-dom"  export const Button = ({ children }) => {   const { pending } = useFormStatus()    return (     <button type="submit" disabled={pending}>       {children} {pending && "Loading..."}     </button>   ) } 
Enter fullscreen mode Exit fullscreen mode

Now we can use it inside the form.

// client component "use client"  import { createPost } from './actions' import { Button } from './Button'  export const Form = () => {   return (     <form action={createPost}>       <input type="text" name="title" />       <input type="text" name="description" />       <Button>Submit</Button>     </form>   ) } 
Enter fullscreen mode Exit fullscreen mode

Handling Errors and Success State

Now to show errors and success messages to the user, we can make use of the useFormState hook. It accepts a Server Action and an Initial State as an argument. It returns the New State and a copy of the Server action.

// client component "use client"  import { createPost } from './actions' import { Button } from './Button' import { useFormState } from "react-dom" import { useEffect } from 'react'  export const Form = () => {   const [createPostState, createPostAction] = useFormState(createPost, {     error: null,     success: false   })    useEffect(() => {     if (createPostState.success) {       alert("Post created!")     }      if (createPostState.error) {       alert(createPostState.error)     }   }, [createPostState])    return (     <form action={createPostAction}>       <input type="text" name="title" />       <input type="text" name="description" />       <Button>Submit</Button>     </form>   ) } 
Enter fullscreen mode Exit fullscreen mode

When using the useFormState hook. Your Server Action will receive an extra argument prevState. So you can modify your server action like this:

"use server"  export const createPost = async (prevState, formData) => {   const title = formData.get("title")   const description = formData.get("description")    if (!title) {     return { error: "Enter the title!", success: false }   }    if (!description) {     return { error: "Enter the description!", success: false }   }    // store the post in the database directly   return { error: null, success: true } } 
Enter fullscreen mode Exit fullscreen mode

Conclusion

Server Actions in Next.Js 14 is an amazing feature. It makes development faster since you don't need a separate backend or API. From creating Server Actions to using them in different scenarios, this guide has provided a comprehensive overview of using Next.Js 14 Server Actions. To learn more about Next.Js 14 and Server Actions, read their official documentation.

  • Next.Js 14 Documentation
  • Server Actions Documentation

MyDevPage: Create a Portfolio Website Instantly

MyDevPage allows you to build a portfolio website in minutes. Focus on building great projects and enhancing your skills rather than wasting your time building a portfolio website from scratch or customizing expensive templates.

MyDevPage handles everything:

  • Portfolio Creation
  • SEO
  • Analytics
  • Customization
  • Custom Domain
  • Contact Form

MyDevPa.ge

javascriptnextjsreactwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.