Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NextJS 13 TypeError: router.events is undefined, next/navigation already imported

Tags:

next.js

I'm trying to show Loading text while the route is loading the url state using the latest nextjs 13, next/router replaced with next/navigation

"use client";
import React, { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import axios from "axios";

const Header = () => {
  const [searchQuery, setSearchQuery] = useState("");
  const [isLoading, setIsLoading] = useState(false); 
  const router = useRouter();

  useEffect(() => {
    const handleStart = () => {
      setIsLoading(true); 
    };

    const handleComplete = () => {
      setIsLoading(false); 
    };

    router.events.on("routeChangeStart", handleStart);
    router.events.on("routeChangeComplete", handleComplete);

    return () => {
      router.events.off("routeChangeStart", handleStart);
      router.events.off("routeChangeComplete", handleComplete);
    };
  }, [router]);

  const handleFormSubmit = async (e) => {
    e.preventDefault();
    setIsLoading(true); 

    try {
      const response = await axios.get(`/result?search_query=${encodeURIComponent(searchQuery)}`);
      const data = response.data;


      console.log("Search Results:", data);

      router.push(`/result?search_query=${encodeURIComponent(searchQuery)}`);
    } catch (error) {
      console.log("Error:", error);
    } finally {
      setIsLoading(false); 
    }
  };

  const handleInputChange = (e) => {
    setSearchQuery(e.target.value);
  };

  return (
    {/* Render data */}
  );
};

export default Header;

Using next/router gives Error: NextRouter was not mounted.

My file is in app/components/Header.jsx, changing to client side to pages/Header.jsx also not working

like image 728
Wan Ahmad Aiman Avatar asked Jan 23 '26 13:01

Wan Ahmad Aiman


1 Answers

i ran in to the same issue

router.events doesn't exist anymore on Next.js 13

doing a quick search on git found some help

https://github.com/vercel/next.js/discussions/42016?sort=new

hope this helps

like image 108
tumi matlala Avatar answered Jan 26 '26 05:01

tumi matlala



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!