Next.js Discord

Discord Forum

Re-render component using <Link> in NextJS 13

Unanswered
Schneider’s Smooth-fronted Caima… posted this in #help-forum
Open in Discord
Schneider’s Smooth-fronted CaimanOP
I have a /products page where I may pass in a URL parameters containing filters (json) for the product list. My navbar will have several links that will redirect to this /products page but with varying filters. What is the best way to do this in Next 13?

next/navigation's <Link> tag changes the url of the page, but doesn't force a re-render, therefore not updating the filters/component.

Everything I can find relating to this just recommends using next/router but it's not supported in Next 13 (afaik). Attempting to use it throws an error that routes to https://nextjs.org/docs/messages/next-router-not-mounted

Am I doing everything wrong here? Is there a better way to pass these filters to the page? Any help is appreciated

3 Replies

@joulev Import useRouter from next/navigation instead of next/router. This is also stated in the link above.
Schneider’s Smooth-fronted CaimanOP
I am using useRouter, it just doesn't refresh my component, it only changes the URL. next/navigation's useRouter is all client-side so it seems to use cached data from the current page. Here's my navbar component:
'use client';
import React, {useState, useEffect} from 'react'
import { useRouter } from 'next/navigation';

export function NavBar() {
    const [links, setLinks] = useState([]);

    const router = useRouter();

    useEffect(() => {
        const fetchData = async () => {
          /* get list of navbar links */
        };
    
        fetchData();
      }, [])

    return (
        <>
            <div className="navbar-wrapper">
                <div className="navbar-container">
                    /* other nav items here */

                    <div className='nav-links nav-flex' >
                        {
                            links.sort((a, b) => a.order - b.order).map((link) => (
                               <button type="button" onClick={() => router.push(
                                        `${link.url}?filters=${encodeURIComponent(JSON.stringify(link.parameters))}`, { shallow: false }
                                    )}>
                                    {link.linkText}
                                </button> 
                            ))
                        }
                    </div>
                </div>
            </div>
        </>
    )
}

export default NavBar
Not sure what’s wrong and not really sure what you are doing in the code