Home > Software design >  Prevent undefined return type for useSWR with TypeScript
Prevent undefined return type for useSWR with TypeScript

Time:02-04

I'm loading data using useSWR and specified the type as a custom interface called MyInterface. I also set fallbackData equal to a default object of type MyInterface. However, TypeScript is asserting that the return type of my data is MyInterface | undefined. How can I make it so that the useSWR does not return an undefined data type, but only a type of MyInterface?

const { data } = useSWR<MyInterface>(
    'myendpoint',
    fetcher,
    {
        fallbackData: {}
    }
);

CodePudding user response:

The useSWR return type states that data may be undefined:

export interface SWRResponse<Data, Error> {
    data?: Data;
    error?: Error;
    revalidate: () => Promise<boolean>;
    mutate: (data?: Data | Promise<Data> | MutatorCallback<Data>, shouldRevalidate?: boolean) => Promise<Data | undefined>;
    isValidating: boolean;
}

Use a type guard to ensure that your data is not undefined:

const { data } = useSWR<MyInterface>(
    'myendpoint',
    fetcher,
);

if(!data) return null; 

// type of data here is always MyInterface

CodePudding user response:

You will always have the option that you won't get data back. Just declare it as MyInterface | undefined and when you want to use it make sure your data is defined

  • Related