The React Router Dom V6 triggers loaders as soon as the router is initialized

I'm currently working on implementing routing into my application using react-router-dom V6, specifically utilizing the new createBrowserRouter function and RouterProvider component.

The issue I'm facing is that when attempting to integrate a loader for the routes (such as the themeLoader), the loader gets triggered right after the router is created in App.tsx.

Although this behavior is expected only on the theme route, it causes problems as the loader fires before the authentication process has even begun or completed, while the queries it initiates require an authenticated user.

Is there a way to delay the execution of the loader until after the authentication process has finished? I've experimented with using shouldRevalidate, but it doesn't prevent the initial firing of the loader.

// PrivateRoute.tsx
function PrivateRoute(Props: PrivateRouteProps) {
  console.log('PrivateRoute!');
  // Authentication logic here
  if (isAuthenticating) return <div>Authenticating...</div>;
  return !isUnauthorised ? <Outlet /> : <div>{'Unauthorised Access'}</div>;
}
// Theme.tsx
export async function themeLoader({ params }: LoaderProps) {
  console.log('themeLoader!');
  const query = store.dispatch(getTheme(params.theme));
  const { data: theme } = await query;
  query.unsubscribe();

  if (theme === undefined)
    throw new Response('Theme Not Found', { status: 404 });
  return theme;
}
// Routes
const themeRoute = {
  path: 'themes/:theme',
  element: <ThemePage />,
  loader: themeLoader
};

const parentRoute = {
  path: '/',
  element: <PrivateRoute authorisedRoles={MemberRoles} />,
  errorElement: <RouteBoundary />,
  children: [themeRoute]
};
// App.tsx
const router = createBrowserRouter([parentRoute]);
// The themeLoader fires at this point...

function App() {
  console.log('App!');
  return <RouterProvider router={router} />;
}
// Console Output
themeLoader!
App!
RouteBoundary!
// Expected Output
App!
PrivateRoute!
themeLoader!

Answer №1

Sorry, it is not possible.

Loaders operate simultaneously, preventing them from interfering with each other or sharing data.

Find more information here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering the 404 Page Not Found error upon refreshing the page while utilizing parallel routes

I'm currently developing a webapp dashboard using the latest version of Next.js 13 with app router. It features a dashboard and search bar at the top. I attempted to implement parallel routes. The @search folder contains the search bar and page.jsx wh ...

Using AJAX to add an event listener and passing parameters to a separate function

Short and sweet - I've got a loop that creates a series of dynamic buttons, and when one of them is clicked, I need to pass its id attribute to another file to generate a new page on the fly. Here's the code snippet: for (var i in data.contacts ...

Having trouble dynamically assigning the ng-model attribute

I am trying to populate the ArrayINeed array, which is the object I need to pass back to the API call. Currently, I am getting undefined for "ConfirmedTrackingReferenceNumbers": Dc.ArrayINeed. Despite researching various posts online and on SO, I have been ...

Discover the magic of observing prop changes in Vue Composition API / Vue 3!

Exploring the Vue Composition API RFC Reference site, it's easy to find various uses of the watch module, but there is a lack of examples on how to watch component props. This crucial information is not highlighted on the main page of Vue Composition ...

What steps should I take to troubleshoot and resolve the connection issue that arises while trying to execute npm install

Following the guidelines from: https://www.electronjs.org/docs/tutorial/first-app I executed commands like mkdir, cd, and npm init. They all ran successfully, generating a file named package.json. Subsequently, I entered npm install --save-dev electron w ...

Enabling Javascript's power-saving mode on web browsers

I created a JavaScript code to play music on various streaming platforms like Tidal, Spotify, Napster, etc., which changes tracks every x seconds. If the last song is playing, it loops back to the first song in the playlist since some websites lack this fe ...

Utilize ng-repeat to display a series of images, with the first image being placed within a unique div

My challenge lies in displaying product images using ng-repeat, where one image is located in a separate div. Let me share my code and explain what is happening. The API response provides product details and images [{"id_product":"1000","name":"Nikolaus ...

In my programming world, 'i' is a mysterious being - always undefined, except when it decides

Currently, I am utilizing Vue, Vuedraggable, and Vuetify in my project. I have encountered an issue where I am unable to use 'let' to define the index for my loop as it always returns undefined. Strangely, using 'var' instead of ' ...

Is there a way for me to retrieve the name of a newly opened browser tab from the original tab?

I have written a code snippet to create a new tab within the same browser by clicking on a link. function newTab() { var form1 = document.createElement("form"); form1.id = "newTab1" form1.method = "GET"; form1.action = "domainname"; //My ...

When a user clicks on a specific accordion, the icon for all accordions under mui control will change

My current task involves mapping over an array of data to render multiple controlled accordions. Each accordion should open/close individually upon clicking, but I'm facing an issue where the icons for all accordions are changing when I interact with ...

Encountering issues while running the npm build command due to exporting async functions in React

In my React project, I am utilizing async functions and have created a file named apiRequest.js structured like this: const axios = require('axios'); const serverURL = "http://localhost:8080" getInfo = async function ({email}) { try { r ...

Is the initial carousel element failing to set height to 100% upon loading?

If you take a look here, upon loading the page you will notice a DIV at the top. It is labeled "content" with "content_container" wrapped around it and finally, "page" around that. Clicking the bottom left or right arrows reveals other DIVs with similar ta ...

How can you connect a property to the output of a method in Vue.js when working with TypeScript and vue-property-decorator?

I'm working with a TypeScript single file vue component. I've encountered an issue where the template does not display the values returned by certain component methods. Here's a snippet of the template: <div class="order-items"> ...

Start by retrieving information and then sending properties to a different component

I have been struggling with this issue for more than a week now. Despite thorough reading of the Next.js documentation and extensive online research, I still can't figure out what's wrong. It seems like I must be overlooking something important, ...

How can we effectively transfer a value from TypeScript/Angular?

I am new to TypeScript and Angular, and I'm struggling with assigning a value to a variable within a function and then using that value outside of the function. In regular JavaScript, I would declare the variable first, define its value in the functio ...

Efficient Loading and Smooth Scrolling with Angular2 (version 7)

I'm struggling to display a component upon the initial page load using lazy loading, where the content is only loaded when it's in view. For instance: - With 10 components on the page, I aim to show/scroll to component number 7 when the page lo ...

Adding a JavaScript widget to a WordPress page

Good morning! I need to place an affiliate external widget on a WordPress page. The code I have loads external content within the page. <script type="text/javascript" src="http://www.convert.co.uk/widget/mobiles.js"></script> The placement o ...

Ways to eliminate a textbox from an HTML table using jQuery or JavaScript while retaining the textbox values

Currently, I am facing a task where I have a table with a column filled with textboxes. My goal is to eliminate the textboxes using jQuery/JavaScript while retaining the values within them. Here are a couple of methods I have attempted: // removes both t ...

Associate a variable with a model within a controller

My goal is to bind a variable in my Controller to a model linked to an input like this: <body ng-app="myApp"> <div ng-controller="MyController"> <input type="text" ng-model="myVar1" /> {{ myVar1 }} <br /> ...

Guide to dynamically generating Angular watchers within a loop

I'm looking to dynamically create angular watches on one or more model attributes. I attempted the following approach: var fields = ['foo', 'bar']; for (var i=0, n=fields.length; i<n; i++) { $scope.$watch('vm.model.&ap ...