Context
I'm using Next.js 13. And I'm using apollo client to store some client side variables.
What i'm trying to do
I'm trying to execute the onClick function prior to navigating to the href location.
My Code
<Link
href={`/session/${session.id}`}
onClick={() => {
updateDialogVars({
dialogOpen: ATTENDANCE_DIALOG,
})
}}
>
<div>
stuff
</div>
</Link>
updateDialogVars is a mutation and updates a reactive vars in apollo client.
Question
Is it possible to use Next.js Link ponent and execute the onClick event before routing takes place with the href? Is the only option to change Link to a div and use next router to push the route change after the onClick function executes?
Context
I'm using Next.js 13. And I'm using apollo client to store some client side variables.
What i'm trying to do
I'm trying to execute the onClick function prior to navigating to the href location.
My Code
<Link
href={`/session/${session.id}`}
onClick={() => {
updateDialogVars({
dialogOpen: ATTENDANCE_DIALOG,
})
}}
>
<div>
stuff
</div>
</Link>
updateDialogVars is a mutation and updates a reactive vars in apollo client.
Question
Is it possible to use Next.js Link ponent and execute the onClick event before routing takes place with the href? Is the only option to change Link to a div and use next router to push the route change after the onClick function executes?
Share asked Mar 7, 2023 at 2:12 NickNick 2958 silver badges14 bronze badges1 Answer
Reset to default 4This is typically achieved with a button and router hook, not an anchor tag (link).
import { useRouter } from "next/router"; // if you use pages dir
import { useRouter } from "next/navigation"; // if you use app dir
const SomeComponent = () => {
const router = useRouter();
const onClick = async () => {
updateDialogVars(...yourConfig);
if(someCondition) {
await router.push(`/session/${session.id}`);
}
}
return (
<button onClick={onClick}>Label</button>
)
}
You can also achieve a similar result with next/link.
import { useRouter } from "next/router"; // if you use pages dir
import { useRouter } from "next/navigation"; // if you use app dir
import Link from "next/link";
const SomeComponent = () => {
const router = useRouter();
const onClick = async (event) => {
event.preventDefault();
updateDialogVars(...yourConfig);
if(someCondition) {
await router.push(event.target.href);
}
}
return (
<Link href={`/session/${session.id}`} onClick={onClick}>Label</Link>
)
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745049445a4608295.html
评论列表(0条)