Here in my code the api is called twice,i see loading data twice in console ,
i tried a few ways like using a varibale to check if loader is already loaded etc,but none of them worked,i am beginner in react so not quite sure how tom fix this i also tried ai platforms but they failed too or gave responses which make the code even worse.so i am hoping i can get help here
import React from 'react';
import { useNavigate, useLoaderData, defer, Await } from 'react-router-dom';
//other imports
export const Loader = () => {
let fetch_data = fetchRequest('', 'GET');
console.log("loading data");
return defer({ loaderPromise: fetch_data });
};
export default function Home() {
const loaderData = useLoaderData();
const navigate = useNavigate();
return (
<div>
<Navbar />
<React.Suspense fallback={<PreLoader />}>
<Await resolve={loaderData.loaderPromise}>
{(resolvedData) => {
if (resolvedData.type === "warning") {
throw new Error(resolvedData.msg);
}
let { coins_list, wallets_list } = resolvedData;
return (
<>
"JSX"
</>
</Await>
</React.Suspense>
<Footer />
</div>
)
}
This is my App.js where i defined Routes
import React from "react";
import { createBrowserRouter, createRoutesFromElements, RouterProvider, Route } from "react-router-dom";
import Home, { Loader as HomeLoader } from "./Pages/Home";
//Components
import Error from './Components/Error';
const App = () => {
const router = createBrowserRouter(
createRoutesFromElements(
<Route path="/" errorElement={<Error />}>
<Route index element={<Home />} loader={HomeLoader} />
</Route>
)
);
return (
<RouterProvider router={router}>
</RouterProvider>
);
}
export default App;
2
Answers
The issue is fixed,the React.StrictMode was interfering twice with the router as i defined it inside my App() function,i just moved it outside the App() and its fixed
Previously :
Fix: "defining router outside App() "
It seems like the issue you’re facing is due to the loader being called twice. This could be because the loader is invoked both as a component (Loader) and within the route definition (loader={HomeLoader}). To resolve this, you should only use one method to load your data.
Since you’re using react-router-dom, you can remove the Loader component and handle data loading directly within the route definition using the loader property.
Try this in app.js
And then, in your Home component, you can fetch data directly using
useLoaderData
hook: