简体   繁体   中英

fix missing dependency warning when missing an object in useEffect React Hook?

So i got a page with a series of switches that are based on the following values:

const [values, setValues] = useState({
    asthma: "off",
    infectiousDisease: "off",
    bleedingDisorder: "off",
    cancer: "off",
    diabetes: "off",
    epilepsy: "off",
    hivAids: "off",
    stroke: "off",
    heartDisease: "off",
    hbp: "off",
    immuneDisorders: "off",
    lungDisease: "off",
    mentalDisorder: "off",
    rheumaticDisease: "off",
    smokeTobaccoProducts: "off",
    radiationTherapy: "off",
    eatingDisorders: "off",
    entDisorders: "off",

    latex: "off",
    localAnasthetics: "off",
    metals: "off",
    penicillin: "off",
    pollen: "off",
    foods: "off",

    bleedingGums: "off",
    bruxism: "off",
    halitosis: "off",
    ulcer: "off",
    dryMouth: "off",
    soreJawM: "off",
  });

Now when a user comes to this page i want the values to be set based on what is saved in the backend. The backend returns a array with the values and i set them in the useEffect(). However i only want this to happen once. This is the code for setting the values from the spring backend.

useEffect(() => {
    getDoH().then(
      (response) => {
        let newValues = values;
        let valueArray = Object.entries(newValues).map((v, index) => {
          v[1] = response.data.switchValues[index]
          return v
      });
      newValues = Object.fromEntries(valueArray);
      setValues({...newValues});
      },
      (error) => {
        console.log(error);
      }
    );
  },[]);

The getDoH function is just a axios.get request. The function works fine however i get this warning in the terminal: "Line 142:5: React Hook useEffect has a missing dependency: 'values'. Either include it or remove the dependency array react-hooks/exhaustive-deps"

Now i know i can disable it but is there anyway to just fix it? adding values to the },[]); is not an option as i dont want it to run every time i change a switch as that basically makes the switches not work.

Any suggestions?

You can pass setValues() a function which updates the state based on the previous state. The function takes the previous state and returns the new state. That way, you don't have to refer to the values defined outside of the useEffect() hook.

For example,

useEffect(() => {
  setValues((state) => generateNewStateFromPrev(state));
}, []);

Here's the documentation on this .

You can store your object as a const rather than in state, and that'd also make your code clearer. react-hooks/exhaustive-deps is correct in the sense that from what the code is, you want to run a function that depends on that values state. So, in a general case, if values changed and the effect depends on it, you'd end up in an inconsistent state.

But your intent is that the code doesn't depend on the state, but on its initial value. You can do something like this.

const defaultIllnesses = {asthma: "off",  infectiousDisease: "off",...};

function myComp () {
  const [values, setValues] = useState(defaultIllnesses);

  useEffect(() => {
    getDoH().then(
      (response) => {
        const valueArray = Object.entries(defaultIllnesses)
   ...
  }, [defaultIllnesses]); // this const is still a dependency, but it won't change 
  

There're some variants, like having illnesses as an array ['asthma', 'infectiousDisease', ...] but that's just syntactic sugar. You can also look into Array.reduce to traverse arrays and create an object out of it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM