JillAndMe
JillAndMe

Reputation: 4551

useEffect for componentDidMount dependency

  1. I use useEffect for using only once when componentDidMount.
  2. I reuse requestPatientsApi in the functional component.
  3. Adding all dependencies in useEffect's second parameter occurs infinity rendering.
  useEffect(() => {
    requestPatientsApi();
  }, []);

  const requestPatientsApi = async (skip: number = 0, limit: number = 100) => {
    try {
      const { data } = await get<AxiosResponse<PatientApi>>("/patient", { skip, limit, requester: "admin" });

      setPager({
        ...pager,
        totalItems: data.totalCount
      });
      props.setPatients(refinedPatients(data.items));
    } catch (err) {
      throw err;
    }
  };

1. How to avoid NO.3's infinity rendering?

2. Is there are any ways to reuse requestPatientsApi avoiding NO.3?

Upvotes: 0

Views: 259

Answers (2)

Shubham Khatri
Shubham Khatri

Reputation: 281754

The missing dependency warning just prompts you to add the dependency in dependency array in case you have missed it but since you are entirely sure that you only want to execute the code once on component mounting you can disable the warning using // eslint-disable-next-line react-hooks/exhaustive-deps

  useEffect(() => {
    requestPatientsApi();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

Upvotes: 1

Abhi Patel
Abhi Patel

Reputation: 224

You can try this

const [toggle, setToggle] = useState(false);
useEffect(() => {
    requestPatientsApi();
  }, toggle);

Upvotes: 0

Related Questions