Next.js Discord

Discord Forum

Fail to get path variable in Next

Unanswered
andrei posted this in #help-forum
Open in Discord
im making my first ever react app w/ next and i struggle with getting the pathname variables

import {Album, parseAlbum} from "@/entities/Album";
import {useEffect, useState} from "react";
import {useRouter} from "next/router";
import {Artist, parseArtist} from "@/entities/Artist";
import {parseSongs, Song} from "@/entities/Song";

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

    const [album, setAlbum] = useState<Album>(parseAlbum({}));
    const [artist, setArtist] = useState<Artist>(parseArtist({}));
    const [songs, setSongs] = useState<Song[]>(parseSongs([]));

    useEffect(() => {
        fetch('http://localhost:8080/albums/' + router.query.id)
            .then((res) => res.json())
            .then((data: object) => {
                setAlbum(parseAlbum(data));
            })
    }, []);

    // more effects

    return (
        <div>
          <!-- -->
        </div>
    );
}

I am getting the router.query.id just fine but after I refresh the page it's undefined. My page looks like /albums/[id].tsx

1 Reply

I also noticed my requests are done twice when I get on the page with a Link (first photo, once with undefined values, once with values) and once with undefined values when I refresh the page in browser (second photo)