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

react router V6.4.3 useLoaderData

I’m new to this and when I used V6.4.3 I found it updated to seem to authenticate using the loader, so I tried to simplify the original method. But when I use useLoaderData(), I get undefined.

Index.js

const router = createBrowserRouter(
  createRoutesFromElements(
    <>
      <Route path="sign-in" element={<SignIn />} />    
      <Route path="/" element={<App />} errorElement={<LayoutError />}>
      <Route
        path="data"
        loader={() => { AuthProvider() }}
        element={<DataLayout />}
      />
      <Route path="about" element={<About />} />
      </Route>
    </>
));
ReactDOM.createRoot(document.getElementById('root'))
  .render(
    <ThemeProvider theme={theme}>
      <RouterProvider router={router} />
    </ThemeProvider>
  );

AuthProvider.js

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

export default function AuthProvider(){
  //{token: '4r8gjifendinsd'}
  const user = authService.getCurrentUser();
  //{"token":"asdasdasd"}
  console.log(JSON.stringify(user));
  if (!user.token) {
    throw redirect("/sign-in");
  }
  return user;
}

DataLayout.js

export default function DataLayout() {
  const user = useLoaderData();
  //undefined
  console.log(user);
}

I checked the official github example, Auth is still the legacy method, and then I checked the manual again carefully, just to make sure that useLoaderData receives JSON. Did I overlook something?

>Solution :

Only thing that appears out of place to me is the loader function not returning any value.

loader={() => { AuthProvider() }} should be:

  • loader={() => {
      return AuthProvider();
    }}
    
  • or more succinctly, loader={() => AuthProvider()}

  • or even more succinctly loader={AuthProvider}

Example:

<Route
  path="data"
  loader={AuthProvider}
  element={<DataLayout/>}
/>
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