I am getting the error while using async, await in useEffect hook.
useEffect(() => {
if (contentLoader) {
(async () => {
try {
const data = await promise;
setData(data);
} catch (errorObj) {
if (!errorObj?.value) { //here i'm getting --> errorObj: unknown Object is of type 'unknown'.
setError(errorObj);
console.log(`loading document error: ${errorObj}`);
}
}
})();
} else // something else
}, [..])
whats wrong in my code.
CodePudding user response:
You're using TypeScript 4.4 or newer with [use-unknown-catch-variables
] (https://devblogs.microsoft.com/typescript/announcing-typescript-4-4/#use-unknown-catch-variables) enabled.
The easiest fix, if you don't know the actual type of the error thrown, is to just tell TypeScript that it's any
, not unknown
.
catch (errorObj) {
->
catch (errorObj: any) {
CodePudding user response:
In TypeScript, catch clause variables may not have a type annotation (aside from, as of TypeScript 4.0, unknown). This is not specific to async. Using TypeScript to infer your custom error type:
interface ApiError {
code: number;
error: string;
}
Now
const isApiError = (x: any): x is ApiError => {
return typeof x.code === 'number';
};
useEffect(() => {
if (contentLoader) {
(async () => {
try {
const data = await promise;
setData(data);
} catch (errorObj) {
catch (error) {
if (isApiError(errorObj)) {
console.log(errorObj)
}
}
})();
} else // something else
}, [..])