Search code examples
reactjstypescriptreact-routerreact-router-dom

Is `fetcher.load` the same as a GET submit?


I try to understand why there is fetcher.load and when to use it.

According to the doc, fetcher.load calls the route's loader. But this is also what fetcher.submit({method: 'GET'}) does. In the following experiment, I don't see any difference. Are there any scenarios under which these two behave differently?

const loader: LoaderFunction = ({ request }) => {
  const url = new URL(request.url)
  console.log("calling loader");
  const data = {"key":"value", url: url}
  return data
}

export const App = () => {
  const fetcher = useFetcher();
  const fetcher2 = useFetcher();

  const handleClick = () => {
    fetcher.load(`/query-data?input=abc`)
  }

  return (
    <div>
      <button onClick={handleClick} >
        click me 
      </button>
      <pre>{ JSON.stringify(fetcher.data, null, 2) }</pre>
      <hr />
      <fetcher2.Form method="GET" action="/query-data">
        <input name="input" value="abc" type="text" readOnly />
        <button type="submit"> submit </button>
      </fetcher2.Form>
      <pre>{ JSON.stringify(fetcher2.data, null, 2) }</pre>
    </div>
  )
}
const root = createRoot(document.getElementById('app'));

const router = createBrowserRouter([
  {
    path: "/",
    element: <App />,
  },
  { /*resource route*/
    path: "/query-data",
    loader: loader
  }
]);

root.render(
  <RouterProvider router={router} />
);

The complete code is in stackblitz


Solution

  • Is fetcher.load the same as a GET submit?

    GET is the default method, so if you don't specify a method, or explicitly specify GET as the method in fetcher.submit, then yes, they are the same.

    fetcher.submit is used to submit a form for the current route whereas the fetcher.load is only used to trigger a specific route's (e.g. href) loader, which are all only GET methods. Other than this I agree, I don't see much of a difference between the two.

    The fetcher.submit appears to offer a bit more configurability over the fetcher.load, e.g. it can use POST, PUT, PATCH, DELETE methods and trigger route actions.