admin管理员组文章数量:1405392
If the current server operation is successful, I need to display a toast message while redirecting to a specific page.
Here are some simple code snippets:
Case 1: Track the state with useActionState
, then call the toast function and router.push
.
const [state, dispatch, isPending] = useActionState(
someAction,
initState()
);
const router = useRouter();
useEffect(() => {
if (state.status !== "success") return;
toast.success(state.message);
router.push(someUrl);
}, [state]);
Case 2: Call the redirect function on the server, passing the desired message in the SearchParams
, and create a component that listens to the SearchParams
to display the toast.
export async function someAction() {
try {
redirect(someUrlWithNotificationParams);
} catch (error) {
throw error;
}
}
export default function Notifier() {
const { searchParams, setSearchParams } = useSearchParams();
useEffect(() => {
if (!searchParams.has(QueryParamKeys.Notification)) return;
const notification = searchParams.get(QueryParamKeys.Notification);
toast.success(notification);
setSearchParams(
(searchParams) => {
const newSearchParams = new URLSearchParams(searchParams);
newSearchParams.delete(QueryParamKeys.Notification);
return newSearchParams;
},
{ replace: true }
);
}, [searchParams, setSearchParams]);
return null;
}
Case 3: Call the redirect function on the server, passing the desired message in a cookie, and create a component that listens to the cookie and displays the toast.
export async function someAction() {
try {
redirect(someUrlWithNotificationParams);
} catch (error) {
throw error;
}
}
export default async function NotificationCookie() {
const cookieStore = await cookies();
return (
<Notifier
notification={cookieStore.get(QueryParamKeys.Notification)?.value}
/>
);
}
export default function Notifier({ notification }: { notification?: string }) {
useEffect(() => {
if (!notification) return;
toast.success(notification);
deleteCookie(); // server action
}, [notification]);
return null;
}
I understand there is no one-size-fits-all answer, but I would like to know which approach is generally recommended from an SEO and performance perspective.
For example, after completing a task such as writing a post, the server generates a new postId and redirects to a new URL. I wonder if replacing the server-side redirect with router.push
might negatively impact SEO.
版权声明:本文标题:next.js - Best practices for redirecting and displaying toast messages after a server action - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744319887a2600443.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论