preactjs / preact-router

:earth_americas: URL router for Preact.
http://npm.im/preact-router
MIT License
1.01k stars 156 forks source link

useRouter hook does not trigger re-render after matching route params #424

Open oliverfindl opened 2 years ago

oliverfindl commented 2 years ago

Hello,

I have issue using useRouter hook and matching route params. Returned context from useRouter hook contains only url key at render time. Later it also contains matches key (that I'm interested in), but at this point it does not trigger re-render of component and I'm stuck only with initial context. Don't know if this is issue on my end, because there is no documentation for this hook. Here is dummy code, that has same logic as my project, but this somehow works while my project does not. Any hints?

// DummyComponent.tsx

import { FunctionalComponent, h } from "preact";
import { useRouter } from "preact-router";

const DummyComponent: FunctionalComponent = () => {
    const [ context ] = useRouter();
    // console.log(JSON.stringify(context), context); // JSON.stringify fails in this dummy component, but works in my project, see screenshot below
    return (
        <div>{context?.matches?.permalinkId ? "OK" : "MISSING"}</div>
    );
};

export default DummyComponent;
// App.tsx

import { FunctionalComponent, h } from "preact";
import { Route, Router } from "preact-router";
import DummyComponent from "./DummyComponent";

const App: FunctionalComponent = () => {
    return (
        <div id="preact_root">
            <Router>
                <Route path="/permalink/:permalinkId+" component={DummyComponent} />
            </Router>
        </div>
    );
};

export default App;

console.log from my project: preact-router-context

Thanks.

oliverfindl commented 2 years ago

Workaround:

const routerContext = useRouter()[0];
const setIncrement = useState<number>(0)[1];
useEffect(() => setIncrement(value => value + 1), [routerContext]);