how to use value of useState after init it

Issue

I these state hook:

     const [features, setFeatures] = useState([])
     const [medicalProblem, setMedicalProblem] = useState([])

my medicalProblem variable will initial with response of a api :

  useEffect(() => {
    getMedicalProblem()
  }, []);

  const initFeatures = (index) => {
    let mfeatures = medicalProblem[index].features //I got Cannot read properties of undefined (reading 'features') error
    mfeatures.sort(function (a, b) {
      return a.order - b.order;
    });
    
    setFeatures(mfeatures)
  }


  const getMedicalProblem = () => {
    api
      .get("dental/generic/slideshow/medical-problem/")
      .then((res: any) => {
        const { count, results } = res
        setMedicalProblem(results)
        initFeatures(0)
        
      })
      .catch((err) => {
        
      });
  };

but I got this error:

Cannot read properties of undefined (reading 'features')

Solution

There are a couple ways to accomplish this, but the easiest may be creating another useEffect hook that depends on the medicalProblems array as seen below!

useEffect(() => {
   if (medicalProblems) {
      initFeatures(0)
   }
}, [medicalProblems])

That extra hook will make sure your medicalProblems are populated before proceeding to initialize your features. Let me know if this works!

Answered By – Amit Maraj

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published