Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why loader function not called in react js?

I am using React-Router-DOM loader prop function (https://reactrouter.com/en/main/route/loader).

<BrowserRouter>
  <Routes>
    <Route
      path={'/ap'}
      loader={() => {
        console.log('0000');
        return 'ss';
      }}
      element={<App />}
    ></Route>
  </Routes>
</BrowserRouter>

When I check on console it is not called or in other words message is not printed.

Here is my code: https://stackblitz.com/edit/vitejs-vite-6gg4ab?file=src%2FApp.tsx,src%2Fmain.tsx&terminal=dev

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function App() {
  const [count, setCount] = useState(0);
  const data = useLoaderData();
  console.log('----s', data);
  return (
    <>
      <div>
        <a href="https://vitejs.dev" target="_blank">
          <img src={viteLogo} className="logo" alt="Vite logo" />
        </a>
        <a href="https://react.dev" target="_blank">
          <img src={reactLogo} className="logo react" alt="React logo" />
        </a>
      </div>
      <h1>Vite + React</h1>
    </>
  );
}

I am trying to fetch some data before routing and I don’t know what I am doing wrong.

>Solution :

Route loaders only work when using Data routers, e.g. routers created using createBrowserRouter, createMemoryRouter, etc. If you would like to use the Data APIs then you’ll need to convert to a Data router.

Examples:

import {
  createBrowserRouter,
  createRoutesFromElements,
  RouterProvider,
  Route,
} from 'react-router-dom';

const router = createBrowserRouter(
  createRoutesFromElements(
    <Route
      path="/ap"
      loader={() => {
        console.log('0000');
        return 'ss';
      }}
      element={<App />}
    />
  )
);

...

<RouterProvider router={router} />
import {
  createBrowserRouter,
  RouterProvider,
  Route,
} from 'react-router-dom';

const router = createBrowserRouter([
  {
    path: "/ap",
    loader: () => {
      console.log('0000');
      return 'ss';
    },
    element: <App />,
  },
]);

...

<RouterProvider router={router} />

For more information see:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading