Home > Enterprise >  Passing type arguments into a custom hook
Passing type arguments into a custom hook

Time:09-17

I'm making a nextjs application and I created a custom useAxios hook, I want to be able make a type assertion like you can do with useState:

const [foo, setFoo] = useState<string>(''); 

But instead I want to pass the type of the response:

const { data, error } = useAxios<CustomResponseType>(URL, true);

How I can accept this type arguments in my function?

CodePudding user response:

The type signature will look something like this:

const useAxios = <T>(URL: string, something: boolean): { data: T, error: any } => {
   // insert code here
}

This is making use of generics.

  • Related