react-router icon indicating copy to clipboard operation
react-router copied to clipboard

[Bug]: the state is not destroyed in the useFetcher hook with key parametr

Open TkachenkoAA opened this issue 1 year ago • 2 comments

What version of React Router are you using?

6.22.3

Steps to Reproduce

Open - demo or demo with source code Click - "FetcherWithKey" Click - "Load fetcher" two times Click - "Other" Click - "FetcherWithKey"

Expected Behavior

'fetcher' should return initial value like IDLE_FETCHER

Actual Behavior

After you return, the fetcher does not destroy the state. And you will see the previously loaded list from page number 2. At the same time, FetcherWithoutKey cleared the previously loaded list

TkachenkoAA avatar Apr 17 '24 17:04 TkachenkoAA

Source code of demo

import { StrictMode, useState } from "react";
import { createRoot } from "react-dom/client";
import {
  Link,
  Outlet,
  useFetcher,
  RouterProvider,
  createBrowserRouter,
  createSearchParams,
  generatePath,
} from "react-router-dom";

const AppLayout = () => {
  return (
    <div>
      <div>
        <Link to={"/fetcherWithKey"}>FetcherWithKey</Link>
        <br />
        <Link to={"/fetcherWithoutKey"}>FetcherWithoutKey</Link>
        <br />
        <Link to={"/other"}>Other</Link>
      </div>
      <Outlet />
    </div>
  );
};

const fakeLoader = async ({ request }) => {
  const url = new URL(request.url);
  const page = Number(url.searchParams.get("page")) || 0;

  const data = Array.from({ length: 15 }, (_, i) => i + page * 15).map(
    (id) => ({
      id,
    })
  );

  await new Promise((res) => setTimeout(res, 500));

  return Promise.resolve({
    data,
    page,
  });
};

const FetcherWithKey = () => {
  const fetcher = useFetcher({ key: "list1Route" });

  const handleFetcher = () => {
    const search = createSearchParams({
      page: String(fetcher.data ? fetcher.data.page + 1 : 0),
    });

    const generatedPath = generatePath(`/fetcherWithKey?${search}`);

    fetcher.load(generatedPath);
  };

  return (
    <div>
      <button onClick={handleFetcher}>Load fetcher</button>
      <pre>{JSON.stringify(fetcher, null, " ")}</pre>
    </div>
  );
};

const FetcherWithoutKey = () => {
  const fetcher = useFetcher();

  const handleFetcher = () => {
    const search = createSearchParams({
      page: String(fetcher.data ? fetcher.data.page + 1 : 0),
    });

    const generatedPath = generatePath(`/fetcherWithoutKey?${search}`);

    fetcher.load(generatedPath);
  };

  return (
    <div>
      <button onClick={handleFetcher}>Load fetcher</button>
      <pre>{JSON.stringify(fetcher, null, " ")}</pre>
    </div>
  );
};

const Other = () => {
  return "OtherRoute";
};

const FetcherWithKeyRoute = {
  path: "/fetcherWithKey",
  element: <FetcherWithKey />,
  loader: fakeLoader,
};

const FetcherWithoutKeyRoute = {
  path: "/fetcherWithoutKey",
  element: <FetcherWithoutKey />,
  loader: fakeLoader,
};

const OtherRoute = {
  path: "/other",
  element: <Other />,
};

const routes = createBrowserRouter([
  {
    path: "/",
    element: <AppLayout />,
    children: [FetcherWithKeyRoute, FetcherWithoutKeyRoute, OtherRoute],
  },
]);

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

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

TkachenkoAA avatar May 01 '24 11:05 TkachenkoAA

It looks to me that this is by design:

Reading here

return state.fetchers.get(key) || IDLE_FETCHER

and the cleanup happening here

// Registration/cleanup
  React.useEffect(() => {
    router.getFetcher(fetcherKey);
    return () => {
      // Tell the router we've unmounted - if v7_fetcherPersist is enabled this
      // will not delete immediately but instead queue up a delete after the
      // fetcher returns to an `idle` state
      router.deleteFetcher(fetcherKey);
    };
  }, [router, fetcherKey]);

It only cleans up when the router changes or the key. If you think this is the wrong behaviour maybe you should rather make a feature request.

hjonasson avatar May 06 '24 02:05 hjonasson