I have a state and use it as index of array of objects. And When I pass that object into other components as props. It gives an Error even though there’s checking:
import React, { Dispatch, useState } from 'react';
import { TestingTwo } from './TestingTwo';
interface Menu {
ItemNumber?: number;
ItemString?: string;
setState?: Dispatch<React.SetStateAction<number>>;
}
export const TestingPage = () => {
const [activeMenu, setActiveMenu] = useState<number>(1);
const [something, SetSomething] = useState<number>(0);
const TestMenu: Menu[] = [
{
ItemNumber: 1,
ItemString: 'test',
setState: SetSomething,
},
];
return (
<>
{TestMenu && TestMenu[activeMenu] && TestMenu[activeMenu].ItemNumber ? (
<TestingTwo
number={TestMenu[activeMenu].ItemNumber || 0}
OnClick={() => TestMenu[activeMenu].setState(1)}
//Cannot Invoke an object which is possibly 'undefined'
/>
) : null}
</>
);
};
The component:
interface TestingTwoProps {
number: number;
OnClick: () => void;
}
export const TestingTwo = ({ number, OnClick }: TestingTwoProps) => {
return <>{number}</>;
};
2
Answers
I have found a workaround for this. But I don't understand why do I have to use a tempFunc to store the setState function first. Can anyone kindly explain to me?
There’s three solutions here:
Update the type of number in
TestingTwo
to number | undefined.The other solution is:
<TestingTwo number={TestMenu[activeMenu].ItemNumber ?? 0} />
(Recommended if you know number will always be required) update your interface from:
interface Menu { ItemNumber?: number; ItemString?: string; }
to:
interface Menu { ItemNumber: number; ItemString?: string; }
Removing the optional
?
on ItemNumberUPDATE FOR SECOND QUESTION
You have the same issue on set state where the interface has it as an optional field.
You make it required by removing the
?
OnClick={() => TestMenu[activeMenu]?.setState()
< update to that where you have a question mark checking if setState existsFINAL EDIT
To get the final bit you need just add the following:
OnClick={() => TestMenu[activeMenu]?.setState(1)
The reason for you error is you were not passing a value to setState