SolidJSS
SolidJSโ€ข3y agoโ€ข
10 replies
elite174

[SPA Routing]: How to not call data function for the protected routes

Let's imagine we have the following app

const App = () => (
  <AuthService>
    <Router>
      <Routes>
        <Route path="/" data={layoutDataFunction} component={LazyPageLayout}>
          <Route path="login" component={LazyLoginPage} />
          <Route path="" component={LazyDefaultLayout}>
            <Route path="content" component={LazyContentPage} data={contentPageDataFunction} />
            {/* Other pages */}
          </Route>
        </Route>
      </Routes>
    </Router>
  </AuthService>
)
;

I handle all auth in the layout data function:
export const layoutDataFunction = ({ navigate, location }: RouteDataFuncArgs) => {
  const { isLogged } = useContext(AuthContext);

  createComputed(() => {
    if (isLogged()) {
      if (location.pathname === "/login") navigate(PagePath.Channel);
    } else {
      if (location.pathname !== "/login") navigate(PagePath.Login);
    }
  });
};


When I enter /content page (unlogin state) the redirect hasn't worked yet, so contentPageDataFunction still fetches the data. I want to not load extra data if I don't need it. How to properly cancel the request for the content page in this case?

Imagine we have the following contentPageDataFunction function:
export const contentPageDataFunction = ({data}) => {
  // I know that here we could get logged state from the parent
  // data function and then inside a resource make this check.
  // However in this case I'll need to change TS types, because
  // it will return <User | null> (if I return null for unlogged state)

  // How to deal with that???
  const [user] = createResource(async () => {
    const result = await myVideosAPI.getMyVideos();

    return result;
  });

  return user;
};


Is there some RIGHT way to do protect routing for SPA apps?
Was this page helpful?