I am new to TS and getting this typeerror in a useEffect() that calls my database. I am not sure what I am doing wrong. I read that it is because I am not returning anything but this function doesn't need to return anything... I could be wrong though.
Argument of type '(res: bookContent) => void' is not assignable to parameter of type '(value: bookContent | undefined) => void | PromiseLike<void>'.
Types of parameters 'res' and 'value' are incompatible.
Type 'bookContent | undefined' is not assignable to type 'bookContent'.
Type 'undefined' is not assignable to type 'bookContent'
Here is the code:
useEffect(() => {
services.bookData
.getBookInfo(bookID)
.then((res: bookContent) => {
if (res) {
setContent({
id: res.id,
name: res.name,
info: res.info,
type: res.type,
});
dispatch(bookContentThunk(content));
}
})
.catch((err: any) => {
throw new Error(`Error in retrieving book details. ${err}`);
});
}, [user.status]);
CodePudding user response:
getBookInfo
can return either bookContent | undefined
(also would advise to add an Uppercase to the bookContent
type to avoid confusion).
You assign a function that describes its argument as (res: bookContent)
. Typescript is complaining that res
can also be undefined
, hence Types of parameters 'res' and 'value' are incompatible.
.
To fix your problem, you should make res
as bookContent | undefined
:
useEffect(() => {
services.bookData
.getBookInfo(bookID)
.then((res: bookContent | undefined) => {
if (res) {
setContent({
id: res.id,
name: res.name,
info: res.info,
type: res.type,
});
dispatch(bookContentThunk(content));
}
})
.catch((err: any) => {
throw new Error(`Error in retrieving book details. ${err}`);
});
}, [user.status]);