Home > Software engineering >  Why do I get infinite requests using useEffect
Why do I get infinite requests using useEffect

Time:07-02

I am trying to create a custom hook function to do data request, but when I call it after creating the hook, the result of infinite request occurs, how can I solve it

this is request hook

export const useRequest = (resource, params) => {
  const [data, setData] = useState();
  const [loading, setLoading] = useState(false);

  const fetcher = (params) => {
    setLoading(true);
    const { page, perPage } = params.pagination;
    const { field, order } = params.sort;
    const query = {
      sort: JSON.stringify([field, order]),
      range: JSON.stringify([(page - 1) * perPage, page * perPage - 1]),
      filter: JSON.stringify(params?.filter ? params.filter : ""),
    };

    http.get(`${resource}?${stringify(query)}`).then((data) => {
      setData(data);
      setLoading(false);
    });
  };

  useEffect(() => {
    fetcher(params);
  }, [params]);

  return {
    data,
    loading,
  };
};

where i call the hook

import { useRequest } from "./hooks/useRequest";

function App() {
  const params = {
    pagination: { page: 1, perPage: 10 },
    sort: { field: "updatedAt", order: "DESC" },
  };
  const { data, loading } = useRequest("/posts", params);

  return (
    <Layout>
      <div className="text-white"></div>
    </Layout>
  );
}

export default App;

CodePudding user response:

There are two things happening here:

  // Create a new object with a new reference every time App renders
  // and send it into useRequest
  const params = {
    pagination: { page: 1, perPage: 10 },
    sort: { field: "updatedAt", order: "DESC" },
  };
  const { data, loading } = useRequest("/posts", params);
  // Every time params reference updates, do a fetch
  useEffect(() => {
    fetcher(params);
  }, [params]);

The best way to remedy is to never update the reference of params, unless its config changes.

const params = useMemo(() => {
  return {
    pagination: { page: 1, perPage: 10 },
    sort: { field: "updatedAt", order: "DESC" },
  };
}, []);

CodePudding user response:

i got anthor solution, use SWR

export const useGetList = (resource, params) => {
  const { page, perPage } = params.pagination;
  const { field, order } = params.sort;
  const query = {
    sort: JSON.stringify([field, order]),
    range: JSON.stringify([(page - 1) * perPage, page * perPage - 1]),
    filter: JSON.stringify(params?.filter ? params.filter : ""),
  };

  const fetcher = (data) => http.get(data).then((res) => res);

  const { data, error } = useSWR(`${resource}?${stringify(query)}`, fetcher);

  return {
    data,
    error,
  };
};

// use
const params = {
    pagination: { page: 1, perPage: 10 },
    sort: { field: "updatedAt", order: "DESC" },
    filter: {},
  };

const { data, error } = useGetList("/posts", params);
  • Related