Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next.js router.query getting undefined on refreshing page, but works if you navigate to it from Link component [duplicate]

Why is router.query empty when I refresh a page with the correct id in the URL, but when when I navigate towards it through , it works?

say I have /pages/[user]/index.js

<Link
  href="/[user]/media/[mediaId]"
  as={`/${username}/media/${post.id}`}
>

this link takes me to localhost:3000/testuser/media/some-id

then in /pages/[user]/media/[mediaId].js

const MediaPage = () => {
  const [post, setPost] = useState([]);
  const router = useRouter();
  const { mediaId } = router.query;


  useEffect(() => {
    router.prefetch("/");
  }, []);

  useEffect(() => {
    if (!mediaId) return null;
    getPostImage();

    async function getPostImage() {
      try {
        const { data } = await API.graphql({
          query: postById,
          variables: {
            id: mediaId,
          },
        });
        setPost(data.postById.items[0]);
      } catch (err) {
        console.log("error getPostImage", err);
      }
    }
  }, [mediaId]);

  if (user === null) return null;

  return (
    <div>
      <Modal
        className={`${styles.postModal}`}
        isOpen={true}
        onRequestClose={() => router.push(`/${user.username}`)}
        contentLabel="Post modal"
      >
        {* // content ... *}
      </Modal>
    </div>
  );
};

export default MediaPage;

When I'm on the media page or localhost:3000/testuser/media/some-id, and press refresh, the mediaId from router.query is empty.

like image 233
hellomello Avatar asked Nov 20 '25 03:11

hellomello


1 Answers

As mentioned by @Ishan Bassi, using the isReady field in next/router would indicate when the query is fully updated after hydration. Therefore, try something like this:

const MediaPage = () => {
  const router = useRouter();

    useEffect(() => {
        if(router.isReady){
            const { media } = router.query;
            if (!mediaId) return null;
            getPostImage();
            ...
         }
    }, [router.isReady]);
   
    ...

}

like image 98
flyingfishcattle Avatar answered Nov 22 '25 17:11

flyingfishcattle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!