Swr: error type in TypeScript

Created on 20 Dec 2019  路  3Comments  路  Source: vercel/swr

Let's say I do this:

const {data, error, isValidating, revalidate} = useSWR<DataType>("/url", myFetcher);

TypeScript tells me that error is typed to be string, but if inside myFetcher I run throw Error("error message"), then the type for error at runtime will not be string, but Error, causing a rendering crash if I try to treat it as text and include it in JSX.

What's going on here? Am I doing something wrong?

Most helpful comment

The second generic property in useSWR is to specify the error type:

typescript jsx const {data, error, isValidating, revalidate} = useSWR<DataType, Error>("/url", myFetcher);

All 3 comments

The second generic property in useSWR is to specify the error type:

typescript jsx const {data, error, isValidating, revalidate} = useSWR<DataType, Error>("/url", myFetcher);

Thanks, I hadn't realized that. That helps.

use a promise with reject:

typescript jsx const myFetcher = (url) => { return new Promise((resolve, reject) => { fetch(url) .then((x) => x.json()) .then(resolve, e => reject('Failed!')) }); };

Was this page helpful?
0 / 5 - 0 ratings

Related issues

bbenezech picture bbenezech  路  5Comments

zahraHaghi picture zahraHaghi  路  3Comments

bywo picture bywo  路  4Comments

frdwhite24 picture frdwhite24  路  4Comments

baoduy picture baoduy  路  4Comments