Home > Enterprise >  How to redirect after or during the onClick function of Button?
How to redirect after or during the onClick function of Button?

Time:11-24

I am trying to add a feature in my Next.js website that allows users to click a button to create a new group, then redirect them to an "Invite members" page that uses the auto generated group_id in the URL with dynamic routing. I am currently using Next.js's Router, but I feel like there is a better (or working) way to do this. JS (within export default function groups ()):

const [num, setNum] = useState("");
const router = useRouter()
const createGroup = async () => {
  const { data, error } = await supabase
    .from("chatgroups")
    .insert([
      {
        group_name: groupName,
        creator: user.email,
        description: groupDesc,
        accepted_members: user.email   " ",
        invited_members: ""
      }
    ]);

  if (error) {
    console.log(error);
  } else {
    setNum("/groups/"   String(data[0].group_id));
    
    router.push(num);
  }
};

HTML (returned in same JS script):

<button type="button" className="bg-yellow-500 rounded px-12 py-2" onClick={()=> {
  createGroup()
  }} >Insert test group</button>

I have tried using the Router for both server and client and both did not recognize .push()

import { Router } from "next/dist/client/router";
import { Router } from "next/dist/server/router"; //neither of these recognized the method.

My goal is to execute the function createGroup(), in which the value of "data" will receive the auto-generated int id of the new SQL row. Then I want to use this id to redirect to "/groups/[id]", where [id] is the new ID. I tried using a Link with the const [num, setNum], but it performs the redirect BEFORE the new value is set. I am relatively new to Next.js, so I would appreciate any help with this.

Desired output: Click button -> adds row to SQL table with group_id = 17. Redirect user to "/groups/invite_members/17".

Edit: I have updated my main JS code above to use useRouter(), now it only works every second click.

CodePudding user response:

The issue is that calling setNum does not update num immediately, as setting state is an asynchronous operation.

This means that on the first button click num will still have its default value ("") when router.push(num) is called, and only when clicking the button a second time will the num state have updated with the value set previously.

To fix it, you can set the value to a variable and use that in the router.push call instead.

const path = "/groups/"   String(data[0].group_id);

setNum(path);

router.push(path);
  • Related