Skip to content

useLocation crashes when used in the onRouteChange callback despite using hte LocationProvider #108

@bloom42-dev

Description

@bloom42-dev

Hello,

We want to implement route guards with preact-iso to redirect unauthenticated users to the login page, in a similar fashion than described in the preact-router docs: https://github.com/preactjs/preact-router#detecting-route-changes, but it seems that it's currently not possible due to a bug.

Describe the bug

The useLocation hook crashes with the following stacktrace when used in the onRouteChange callback of the Router component.

Uncaught (in promise) TypeError: can't access property "context", r is null
    Preact 2
        x
        useLocation
    onRouteChange app.tsx:68
    Preact 7
        Router
        B
        __h
        __c
        __c
        N
        $
    debounceRendering debounceRendering.js:13
    promise callback*options.debounceRendering debounceRendering.js:11
    Preact 10
        M
        setState
        __
        LocationProvider
        B
        __h
        __c
        __c
        N
        G
    <anonymous> app.tsx:99
2 [index.js:372:19](preact/hooks/src/index.js)
    debounceRendering debounceRendering.js:16
    (Async: promise callback)
    debounceRendering debounceRendering.js:11
    Preact 6
    filter self-hosted:195
    __c Preact
    some self-hosted:137
    Preact 3
    <anonymous> app.tsx:99

To Reproduce

import { render } from 'preact';
import { LocationProvider, Router, Route, useLocation } from 'preact-iso';

function App() {
  function onRouteChange() {
    // crash here
    const location = useLocation();
    console.log(location);
  }

  return (
    <LocationProvider>
      <a href="/">A</a> | <a href="/b">B</a>
      <Router onRouteChange={onRouteChange}>
        <Route path="/" component={A} />
        <Route path="/b" component={B} />
      </Router>
    </LocationProvider>
  );
}

function A() {
  return (
    <div>
      <h1>A</h1>
    </div>
  )
}

function B() {
  return (
    <div>
      <h1>B</h1>
    </div>
  )
}


render(<App />, document.getElementById('app'));

Navigate between the links and look at the console. You will see the call to useLocation() crashing.

Expected behavior

We expect to be able to use the useLocation hook in onRouteChange in order to programmatically redirect (using route) users to another route depending on the URL / app state.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions