Next.js Discord

Discord Forum

How to pass data from a form to another page

Unanswered
Sloth bear posted this in #help-forum
Open in Discord
Sloth bearOP
Hello, I am trying to have the user type in their username in a main page and after submitting get redirected to a second page which shows just the image with their stats retrieved from an API.

I keep getting this error:

Unhandled Runtime Error
TypeError: Cannot destructure property 'name' of 'router.query' as it is undefined.

Source
src\app\profile\[name]\page.js (8:10) @ name

   6 | export default function Profile() {
   7 | const router = useRouter();
>  8 | const { name } = router.query;

Main page:
import { useRouter } from 'next/navigation';

export default function Home() {
  const router = useRouter();

  const handleSubmit = async (event) => {
    event.preventDefault();
    const formData = new FormData(event.target);
    const name = formData.get('name');
    console.log('name:', name);

    // Redirect to the Profile page with the username as a parameter
    router.push(`/profile/${encodeURIComponent(name)}`);
  };


Form in main page:
<form onSubmit={handleSubmit}>
          <label htmlFor="name">
            <input   
              placeholder="Enter your EPIC name"
              name="name"
              type="text"
              id="name"
            />
          </label>
          <div className="ml-1">
            <button>
              View Stats
            </button>
          </div>
        </form>


Profile page:
import { useRouter } from 'next/navigation';

export default function Profile() {
  const router = useRouter();
  const { name } = router.query;
  const [statsData, setStatsData] = useState(null);
  const apiKey = process.env.API_KEY;

The URL appears correctly, so like: http://localhost:3000/profile/name

But the profile page is not getting the name parameter to make the API work.

1 Reply

router.query was removed in favor of the useSearchParams hook.

See: https://nextjs.org/docs/app/api-reference/functions/use-router#migrating-from-nextrouter