S
SolidJS6mo ago
Karl

changing route with useNavigate() causes onMount() of the child route to be fired twice

Hey, i have a problem that i cant wrap my mind. When i load my Route in a new window/tab or with F5 the onMount() function of one of my children is only fired one. But when i use useNavigate(), then onMount() gets fired twice. Why could that be? I am working on replicating the bug.
1 Reply
Karl
KarlOP6mo ago
Okay the issue arises because of <Suspense>
// App.tsx
<Router>
<Route path='/' component={Home}></Route>

<Route path='/test' component={Test}>
<Route path='/hallo1' component={Hallo}></Route>
<Route path='/hallo2' component={Hallo2}></Route>
</Route>
</Router>
// App.tsx
<Router>
<Route path='/' component={Home}></Route>

<Route path='/test' component={Test}>
<Route path='/hallo1' component={Hallo}></Route>
<Route path='/hallo2' component={Hallo2}></Route>
</Route>
</Router>
function Test(props: any){

async function fetchTest(){
return new Promise(async (resolve, reject) => {

setTimeout(() => {
resolve('nice')
}, 2000)
})
}

const [ok, {mutate, refetch}] = createResource<any, any>(fetchTest)

return(
<div>
<Suspense>

<p>{ok()}</p>
{props.children()}
</Suspense>

</div>
)
}
function Test(props: any){

async function fetchTest(){
return new Promise(async (resolve, reject) => {

setTimeout(() => {
resolve('nice')
}, 2000)
})
}

const [ok, {mutate, refetch}] = createResource<any, any>(fetchTest)

return(
<div>
<Suspense>

<p>{ok()}</p>
{props.children()}
</Suspense>

</div>
)
}
function Hallo(props: any){
const navigate = useNavigate()

onMount(() => {
console.log('hallo1')
})

return(
<div>
<button
onclick={(() => {
navigate('/test/hallo2')
})}
>/hallo2</button>
</div>
)
}
function Hallo(props: any){
const navigate = useNavigate()

onMount(() => {
console.log('hallo1')
})

return(
<div>
<button
onclick={(() => {
navigate('/test/hallo2')
})}
>/hallo2</button>
</div>
)
}
function Hallo2(props: any){
const navigate = useNavigate()

onMount(() => {
console.log('hallo2')
})

return(
<div>
<button
onclick={(() => {
navigate('/test/hallo1')
})}
>/hallo1</button>
</div>
)
}
function Hallo2(props: any){
const navigate = useNavigate()

onMount(() => {
console.log('hallo2')
})

return(
<div>
<button
onclick={(() => {
navigate('/test/hallo1')
})}
>/hallo1</button>
</div>
)
}
Now when i click the buttons with onclick -> useNavigate(), the onMount() function of the subroutes gets executed twice. Any idea how to solve this? Okay the problem was solved for me by usind <Show when={!ok.loading}> instead of Suspense. I still cant quite wrap my mind around it. Can someone hint me to resources to understand it?
Want results from more Discord servers?
Add your server