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
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?
CodePudding user response:
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/>}
/>