The current implementation of calling the API from the App.jsx file is not necessarily wrong, but it may not be the best practice. A better approach would be to create a separate file for handling API calls and then import that file into the component where the data is needed. This way, the component is only responsible for rendering the data and not fetching it.
Here's an example of how to implement this:
- Create a new file called
api.jsand define thefetchDatafunction in it:
export async function fetchData() {
const response = await fetch('https://example.com/api/data');
const data = await response.json();
return data;
}
- Import the
fetchDatafunction into theApp.jsxfile:
import { fetchData } from './api';
const router = createBrowserRouter([
{
element: <Layout />,
errorElement: <ErrorPage />,
children: [
{
path: '/',
element: <Home />,
loader: fetchData,
},
],
},
]);
This way, the fetchData function is separated from the component and can be reused in other components as well.