Home > Back-end >  how to use value of useState after init it
how to use value of useState after init it

Time:04-30

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')

CodePudding user response:

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!

  • Related