i get error cannot read property of undefined using react and typescript?
what i am trying to do?
i have a parentComponent within which i make a query to get some data "itemData". and pass this itemData to the ChildComponent.
in the childComponent i am getting one property from itemData that is availableItems and passing it to Select menu options.
below is the code,
const ParentComponent = () => {
const itemData = useItemDataQuery();
return (
<ChildComponent itemData={itemData.data}/>
);
}
const ChildComponent =(itemData: any) => {
const options = react.useMemo(() => { //error here
const output = itemData && itemData[0].availableItems;
return output;
}
}, [itemData]);
return (
<SelectMenu options ={options} value="hello"/>
);
}
itemData is an array of object like below
const itemData = [
{
name: 'name1',
availableItems: [
'Item1',
'Item2',
],
}
]
i am accessing availableItems with itemData && itemData[0].availableItems but still giving an error.
Could someone help me fix this. thanks.
EDIT:
I have tried like below
const options = react.useMemo(() => {
if (itemData && itemData.length > 0) {
const output = itemData[0].availableItems;
return output;
}
}
}, [itemData]);
this works. but under SelectMenuComponent the prop options shows error "no overload matches this call. Type Maybe<string>[]|undefined|null is not assignable to type .
return (
<SelectMenu options ={options} value="hello"/> //error here
);
could someone help me with this. thanks.
react seems to be undefined.
Just add this statement at top of your imports:
import React from "react";
and use React.useMemo