Search code examples
reactjsreact-routerreact-router-dom

How to trigger Loader function of index route (not parent route) using useFetcher().load() in react-router-dom


I have these structure of Links in Index.js

// all imported stuff is working

const router = {
      path: '/events',
      element: < EventsLayout / > ,
      /*loader: EventsLoader, fetcher can tigger it here*/
      children: [{
        index: true,
        element: < Events / > ,
        loader: EventsLoader /** Cannot here */
      }, ]
    }]
},


const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <RouterProvider router={router}>
      <App />
    </RouterProvider>
  </React.StrictMode>
);

when i want trigger loader that located in index route by executing this line

./pages/About.jsx

import {useFetcher} from 'react-router-dom'
import {useEffect} from 'react'

const About = () => {
   const fetcher = useFetcher();

   useEffect(_=> {

      fetcher.load("/events");

   }, [])

   return <h1>About Page</h1>;
}

it doesn't trigger it! but when I located loader function in parent path not index, it worked fine

so my question is, how to trigger loader that existed in **index** route(child) of parent path?


Solution

  • From the fetcher.load docs:

    Although a URL might match multiple nested routes, a fetcher.load() call will only call the loader on the leaf match (or parent of index routes).

    I've emphasized a relevant section that explains the behavior you ask about. The parent Route component is the route in the configuration with a specific path property so I believe index routes need to look to their parent route's loader functions to work properly.

    so my question is, how to trigger loader that existed in index route(child) of parent path?

    Basically, you can't. The index routes can call the loader function of their parent layout route.