preactjs / preact-router

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

Redirecting no longer appears to work on first render #417

Open Worble opened 2 years ago

Worble commented 2 years ago

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.

TuureKaunisto commented 2 years ago

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.

premasagar commented 2 years ago

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

setTimeout(() => route('/', true), 0);
9Morello commented 9 months ago

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

bobjohnbob commented 8 months ago

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?

ShivamJoker commented 7 months ago

Also having the same issue