Next.js Discord

Discord Forum

How to use server action to Button click to navigate to url using server actions ?

Answered
Asiatic Lion posted this in #help-forum
Open in Discord
Asiatic LionOP
In my app service route is a use client where I have a button, when clicked calls a function to navigate to a url. For some security reason I can't use in link component. The same button function is being used in 3 cards. Which takes the title name. And according to title it navigates to url. I am using api to do this. How to do the same using server actions.

const handlePricingClick = async (prodName) => { try { const response = await fetch(${process.env.NEXT_PUBLIC_BASE_URL}/api/getPayment,{ method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ productName: prodName }), }); if (response.status === 200) { const data = await response.json(); router.push(data.url); } else { console.log("error!"); } } catch (error) { console.log(error); console.log("failed to create order this is an error"); } };
Answered by B33fb0n3
Sure. This is a server action:
// Server Component
export default function Page() {
  // Server Action
  async function create() {
    'use server'
 
    // ...
  }
 
  return (
    // ...
  )
}

And that's one for client side:
'use server'
 
export async function create() {
  // this code will be executed serverside

  redirect("/some/where/")
}
View full answer

5 Replies

Asiatic LionOP
@B33fb0n3 I have no idea about server action. Will it be possible for you to provide a example code?
@Asiatic Lion <@301376057326567425> I have no idea about server action. Will it be possible for you to provide a example code?
Sure. This is a server action:
// Server Component
export default function Page() {
  // Server Action
  async function create() {
    'use server'
 
    // ...
  }
 
  return (
    // ...
  )
}

And that's one for client side:
'use server'
 
export async function create() {
  // this code will be executed serverside

  redirect("/some/where/")
}
Answer
@Asiatic Lion Thank you 😊
Sure thing. Please mark solution