I these state hook:
JavaScript
x
3
1
const [features, setFeatures] = useState([])
2
const [medicalProblem, setMedicalProblem] = useState([])
3
my medicalProblem
variable will initial with response of a api :
JavaScript
1
28
28
1
useEffect(() => {
2
getMedicalProblem()
3
}, []);
4
5
const initFeatures = (index) => {
6
let mfeatures = medicalProblem[index].features //I got Cannot read properties of undefined (reading 'features') error
7
mfeatures.sort(function (a, b) {
8
return a.order - b.order;
9
});
10
11
setFeatures(mfeatures)
12
}
13
14
15
const getMedicalProblem = () => {
16
api
17
.get("dental/generic/slideshow/medical-problem/")
18
.then((res: any) => {
19
const { count, results } = res
20
setMedicalProblem(results)
21
initFeatures(0)
22
23
})
24
.catch((err) => {
25
26
});
27
};
28
but I got this error:
JavaScript
1
2
1
Cannot read properties of undefined (reading 'features')
2
Advertisement
Answer
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!
JavaScript
1
6
1
useEffect(() => {
2
if (medicalProblems) {
3
initFeatures(0)
4
}
5
}, [medicalProblems])
6
That extra hook will make sure your medicalProblems are populated before proceeding to initialize your features. Let me know if this works!