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?
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!'))
});
};
Most helpful comment
The second generic property in
useSWRis to specify the error type:typescript jsx const {data, error, isValidating, revalidate} = useSWR<DataType, Error>("/url", myFetcher);