I'm working on a front-end app using React, Typescript, Effector, FetchAPI and more. I made an Effector effect to delete an item in my backend:
export const deleteItemFX = createEffect({
handler: (id: string) => {
return fetch(itemUrl + id, {
method: "DELETE",
});
}
})
Now in my React component, I import my effect and add a subscriber to its 'finally' event, as per the documentation:
deleteItemFX.finally.watch(({params, status, result}) => {
console.log('finally.watch called');
if (result.ok) {
result.json().then(() => {
message.success(t("delete_item.success"));
})
}
});
My code does not compile because of the following type error:
Property 'result' does not exist on type '{ status: "done"; params: string; result: Response; } | { status: "fail"; params: string; error: Error; }'. TS2339
Does anyone know what I can do to get the 'result' of my handler in my 'finally.watch' function?
The problem is that you're trying to pull out the property
resultwhen you destructure the argument towatch, before you check whetherstatusequals"done"or"fail".Look at the error message: the property
resultdoes not exist on the type:This is a union of two object types; to read a property from a union, that property must exist on both sides of the union.
resultonly exists on the first case, not on the second. So before you try to read it, you need to make sure that the data you have belongs to the first case. You do this by using anifstatement to refine the type: