2

I'm new to Solid JS, coming mainly from a React background. I'm using Solid and Solid-App-Router right now for the first time.

I'm trying to design routes with a fallback, meaning if an endpoint is put into the URL that does not exist, it will redirect to a default location. My problem is this fallback is executing no matter what, overriding all my other routes.

I'll add that namedLazy works great and is simply a wrapper to support named exports with SolidJS lazy(). Here is my routing code:

import { namedLazy } from '../../utils/solidWrappers';
import { Routes, Route } from 'solid-app-router';
import { isAuthenticated } from '../../resources/AuthResources';

const Welcome = namedLazy(() => import('./Welcome'), 'Welcome');

const Categories = namedLazy(() => import('./Categories'), 'Categories');

const Redirect = namedLazy(() => import('../UI/Redirect'), 'Redirect');

export const AppRoutes = () => {
    return (
        <Routes>
            <Route path="/welcome" element={<Welcome />} />
            {isAuthenticated() && (
                <Route path="/categories" element={<Categories />} />
            )}
            <Route path="*" element={<Redirect />} />
        </Routes>
    );
};

And here is my Redirect component:

import { useNavigate } from 'solid-app-router';

export const Redirect = () => {
    const navigate = useNavigate();
    navigate('/welcome');
    return <></>;
};

This kind of fallback route design works in react-router, however it's not working for me with solid-app-router. This is not the only route design, I also tried the configuration/array based route design as well and had the same problem. I'm open to suggestions for how to properly implement this functionality.

craigmiller160
  • 5,751
  • 9
  • 41
  • 75
  • 1
    I have an imitation of your code in stackblitz, and I don't see any issue with the fallback overriding the other routes. Link: https://stackblitz.com/edit/vitejs-vite-xeugum – FoolsWisdom Jun 27 '22 at 19:07

1 Answers1

2

As the other commenter said, my code for the fallback route actually does work. This was a reactivity issue.

When the page first loads, isAuthenticated() returns false, because the authentication check is an ajax call that hadn't run yet. Therefore the /categories route wouldn't be rendered, and if I was trying to manually navigate to /categories I would instead by redirected. This made it appear as though the catch-all route was overriding everything, when in fact it was behaving as expected.

I added another check to prevent the routes from rendering until after the authentication check ajax call was made, and then everything worked perfectly.

halfer
  • 19,824
  • 17
  • 99
  • 186
craigmiller160
  • 5,751
  • 9
  • 41
  • 75