I am using react-router 7.1.3 and I am facing a problem with loader. I am not sure how to use it and the tutorial I am following is using react-router-dom which is very different from the new version.
App.jsx
import './App.css'
import { Routes, Route } from "react-router";
import Homepage from './Pages/HomePage/Homepage';
import Store from './Pages/Store/Store';
import About from './Components/About';
import Blog from './Components/Blog';
import Navbar from './Components/Navbar';
import SingleBook from './Pages/Store/SingleBook';
function App() {
return (
<>
<Navbar />
<Routes>
<Route path='/' element={<Homepage />} />
<Route path='/store' element={<Store />} />
<Route path='/about' element={<About />} />
<Route path='/blog' element={<Blog />} />
<Route
path='/book/:id'
element={<SingleBook />}
loader={({ params }) =>
fetch(`http://localhost:3000/books/book/${params.id}`)}
/>
</Routes>
</>
)
}
export default App
The poblem I am facing is in the route to /book/:id
. The errors I am getting are:
Uncaught Error: useLoaderData must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.
at invariant (react-router.js?v=2d8b4bb3:1189:11)
at useDataRouterState (react-router.js?v=2d8b4bb3:5492:3)
at useLoaderData (react-router.js?v=2d8b4bb3:5552:15)
at SingleBook (SingleBook.jsx:5:17)
at renderWithHooks (chunk-VIJJTZRL.js?v=2d8b4bb3:11596:26)
at mountIndeterminateComponent (chunk-VIJJTZRL.js?v=2d8b4bb3:14974:21)
at beginWork (chunk-VIJJTZRL.js?v=2d8b4bb3:15962:22)
at HTMLUnknownElement.callCallback2 (chunk-VIJJTZRL.js?v=2d8b4bb3:3680:22)
at Object.invokeGuardedCallbackDev (chunk-VIJJTZRL.js?v=2d8b4bb3:3705:24)
at invokeGuardedCallback (chunk-VIJJTZRL.js?v=2d8b4bb3:3739:39)
and in SingleBook.jsx I have written:
import { useLoaderData } from "react-router"
const SingleBook = () => {
const { _id } = useLoaderData();
return (
<div>
Single Book: {_id}
</div>
)
}
export default SingleBook
Package.json
{
"name": "frontend",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"autoprefixer": "^10.4.20",
"postcss": "^8.5.1",
"prop-types": "^15.8.1",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-icons": "^5.4.0",
"react-router": "^7.1.3",
"swiper": "^11.2.1",
"tailwindcss": "^3.4.17"
},
"devDependencies": {
"@eslint/js": "^9.17.0",
"@types/react": "^18.3.18",
"@types/react-dom": "^18.3.5",
"@vitejs/plugin-react": "^4.3.4",
"eslint": "^9.17.0",
"eslint-plugin-react": "^7.37.2",
"eslint-plugin-react-hooks": "^5.0.0",
"eslint-plugin-react-refresh": "^0.4.16",
"globals": "^15.14.0",
"vite": "^6.0.5"
}
}
I have tried to search about it and nothing seems to be of help. Should I downgrade to react-router-dom or can I use the loader function in this version as well?