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.

本文标签: nextjsBest practices for redirecting and displaying toast messages after a server actionStack Overflow