preact-router icon indicating copy to clipboard operation
preact-router copied to clipboard

Redirecting no longer appears to work on first render

Open Worble opened this issue 3 years ago • 5 comments

Hi, I just updated to v4.0.1 and was trying to use a redirect component as shown in the docs, but redirecting no longer appears to work on the initial render. See the JSFiddle here: https://jsfiddle.net/vgo2p4b6/1/ - the first render should redirect to Johns Profile, but nothing is matched instead, and clicking the home button anytime after that redirects as expected. I've tried using the new useRouter to no success either, the second array item method works the same. Using the router.routeTo method from the first array item renders the correct component, but does not update the url.

Worble avatar Jan 24 '22 21:01 Worble

We had the same issue and switching from componentDidMount to useEffect seemes to work but there might be some edge cases where this is not equivalent.

import { FunctionalComponent } from 'preact'
import { useEffect } from 'preact/hooks'
import { route } from 'preact-router'

interface RedirectProperties {
  to: string
}

const Redirect: FunctionalComponent<RedirectProperties> = ({ to }: RedirectProperties) => {
  useEffect(() => {
    route(to, true)
  }, [to])

  return null
}

export default Redirect

The readme should probably be updated to have a working example of how to do redirects.

TuureKaunisto avatar Feb 10 '22 07:02 TuureKaunisto

A workaround is to use setTimeout, and call route() in the callback:

setTimeout(() => route('/', true), 0);

premasagar avatar Jul 04 '22 14:07 premasagar

Still having this issue on 4.1.2. @premasagar your workaround still works btw

9Morello avatar Jan 21 '24 16:01 9Morello

I'm running into the same problem. It seems this is caused when you call route on the first render because the recently mounted Router component has not yet been added internally to the list of Routers. I think using componentWillMount instead of componentDidMount to add the Router to the list of ROUTERS would fix the problem. See: https://github.com/preactjs/preact-router/blob/93f1cda38c1afe36ca643914d560544d3c9f44bd/src/index.js#L187-L194

I'm not sure if this would cause other problems though. Can anyone give any insight to this?

bobjohnbob avatar Feb 26 '24 21:02 bobjohnbob

Also having the same issue

ShivamJoker avatar Mar 25 '24 11:03 ShivamJoker