Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

182
Views
How to resolve dependency array warning in React when variable is conditional?

I am doing a fetch request in useEffect hook. It is how it looks like.

useEffect(() => {
    // clear prev state
    setUniqueValues([]);
    setLoading(true);

    // get unique values and set field values;
    jwtAxios
        .post(`${baseURL}/support/get_unique_values`, {
            field: fieldName,
            catalog_id: catalogID,
            page,
            category_values: props?.initialValues?.schema?.category,
        })
        .then((data) => {
            setUniqueValues(data.data.unique_values);
            setLoading(false);
            setError(false);
        })
        .catch((err) => {
            console.log(err);
            setError(err);
        });
}, [catalogID, fieldName, page]);

In the post request I want to send a value (category_values) if it is exists, if it comes with props. so I check with ?.

But if I don't put it in dependency array it complains:

warning  React Hook useEffect has a missing dependency: 'props?.initialValues?.schema?.category'. Either include it or remove the dependency array  react-hooks/exhaustive-deps 

If I add it like [catalogID, fieldName, page,props?.initialValues?.schema?.category ]

It complains like :

  Line 100:8:   React Hook useEffect has a missing dependency: 'props.initialValues.schema.category'. Either include it or remove the dependency array    react-hooks/exhaustive-deps
  Line 100:37:  React Hook useEffect has a complex expression in the dependency array. Extract it to a separate variable so it can be statically checked  react-hooks/exhaustive-deps

If I don't put ?'s when props are not passed, it is collapsing because it doesn't find props.

How do I solve it? Thanks.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

you can compute the category just before calling useEffect

const category = props?.initialValues?.schema?.category;

useEffect(() => {
    setUniqueValues([]);
    setLoading(true);

    jwtAxios
        .post(`${baseURL}/support/get_unique_values`, {
            field: fieldName,
            catalog_id: catalogID,
            page,
            category_values: category,
        })
        ...
}, [catalogID, fieldName, page, category]);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!