I have a React Hook which is used in several forms to get data from an API call. The target URL is defined using parameters to the hook. The returned object could be one of several types depending upon the component using the hook, I've included an extract below:
export const useFormControl = (
feature: Feature,
id?: string,
) => {
const [{ data, error, loading}] = useAxios({
url: `https://this.is.the.url?feature=feature&id=id`,
});
...
return {
data,
error,
loading,
...
} as const;
};
And I'm using the effect as below:
const FormType1 = {
prop1 : string;
prop2: string
}
export const Form = ({ ... }: FormProps) => {
const [formData, setFormData] = useState<FormType1>();
const {
data,
error,
loading,
...
} = useFormControl(mode,id);
useEffect(() => {
if (data) {
setFormData(data as FormType );
}
}, [formData]);
// use formData here...
}
This pattern is repeated many times. I would prefer not to have to have a useEffect in each component using the hook to cast the incoming data to the FormType for that form. Is there a way to use generics to 'type' the custom hook so that the data of the useAxios hook can be the correct type?