vincent15000's avatar

React, createBrowserRouter and the route loader

Hello,

I'm learning React and I wonder if this is the right way to define a route with loading datas.

This is the content of the App.jsx file.

async function fetchData() {
	const datas = ...
	return datas;
}

const router = createBrowserRouter([
  {
    element: <Layout />,
    errorElement: <ErrorPage />,
    children: [
      {
        path: '/',
        element: <Home />,
        loader: fetchData,
      },
    ],
  },
]);

Isn't it strange to have to call the API from the App.jsx file. For me it's like I would call the API from the web.php file in Laravel.

Can you help me to understand how I could do ? Or it's perhaps the right way ?

Thanks a lot ;).

V

0 likes
1 reply
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

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:

  1. Create a new file called api.js and define the fetchData function in it:
export async function fetchData() {
  const response = await fetch('https://example.com/api/data');
  const data = await response.json();
  return data;
}
  1. Import the fetchData function into the App.jsx file:
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.

1 like

Please or to participate in this conversation.