Home > Software engineering >  Cannot invoke an object which is possibly 'undefined'. ReactTypescript by passing state se
Cannot invoke an object which is possibly 'undefined'. ReactTypescript by passing state se

Time:10-12

I am passing a state prop from parent to child:

Parent:

const [refresh, setRefresh] = React.useState<boolean>(true);

passing into Component as

<Chart setRefresh={setRefresh}/>

Child

interface IChart {
    refreshChart?: boolean;
    setRefresh?: (newRefresh: boolean) => void;
}

const Chart: React.FunctionComponent<IChart> = ({refreshChart, setRefresh}) => {

   const handleRefresh = () => {
      setRefresh(false);
   }

}

Obviously it's to do with the type in the IChart interface as if I use any or not make it optional it works, but I need it optional and want to avoid any.

CodePudding user response:

it's because in IChart interface you're saying that this property is optional, so it is "possibly undefined". Just remove "?" from setRefresh if the value is required.

CodePudding user response:

Obviously it's to do with the type in the IChart interface as if I use any or not make it optional it works, but I need it optional and want to avoid any.

If you want to keep the property optional, then you have to deal with the fact it's optional, either by making the call to it check first:

const Chart: React.FunctionComponent<IChart> = ({refreshChart, setRefresh}) => {
    const handleRefresh = () => {
        if (setRefresh) {         // ***
            setRefresh(false);
        }
    };
}

...or by having a default:

const Chart: React.FunctionComponent<IChart> = ({refreshChart, setRefresh = (b: boolean) => {}}) => {
//                                                                       ^^^^^^^^^^^^^^^^^^^^^
    const handleRefresh = () => {
        setRefresh(false);
    };
}

You might even make creating handleRefresh conditional based on whether setRefresh exists, and possibly even change what the component renders (e.g., no refresh UI) if setRefresh isn't provided.

CodePudding user response:

I do with Similar cases a simple if condition basically because if tweak it a teammate may come in the future and integrate it wrongly, or add a default value to it

 const handleRefresh = () => {
     if(setRefresh)
      setRefresh(false);
   }

  • Related