Thank you for providing that additional information. The error you're encountering is related to how redirect() functions in Next.js, particularly within server actions and try/catch blocks. Let me explain the issue and provide a solution based on the knowledge sources.
The NEXT_REDIRECT error you're seeing is actually an internal Next.js mechanism for handling redirects. According to a GitHub issue comment (https://github.com/vercel/next.js/issues/59930), this is expected behavior:
Because APIs such as redirect and notFound interrupt program execution by throwing exceptions that Next.js can handle.
The problem occurs because the redirect() function is being called inside a .then() block, which is essentially a try/catch structure. To resolve this, we need to adjust where and how we use the redirect() function.
Here's a suggested solution:
- Move the
redirect() call outside of the .then() block.
- Use a state or ref to store the leaderboard entry ID.
- Use the
useEffect hook to perform the redirect after the state has been updated.
Here's how you could modify your code:
"use client";
import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
const [leaderboardEntryId, setLeaderboardEntryId] = useState(null);
const router = useRouter();
useEffect(() => {
if (leaderboardEntryId) {
router.push(`/results/${leaderboardEntryId}`);
}
}, [leaderboardEntryId, router]);
const userLeaderboardEntry = addLeaderboardEntryToGame({
}).then(leaderboardEntry => {
console.log("Leaderboard entry added:", leaderboardEntry);
setLeaderboardEntryId(leaderboardEntry);
});