Reputation: 4711
In a ReactNative component, when I press a button I got the "Possible Unhandled Promise Rejection" error when I execute this function:
async onAdd(item) {
try {
const response = await fetch('url', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
event_id: item.id,
event_type: item.event_type,
})
});
const responseJson = await response.json();
} catch (error) {
error(error);
}
}
I do not know why since its in a try / catch block.
UPDATED
This is the error function:
function error(value) {
if (console) {
console.error(value)
}
}
Upvotes: 5
Views: 12445
Reputation: 707326
The problem is you are redefining the symbol error
here with the catch
argument:
} catch (error) {
error(error);
}
so that hides your error()
function. Change to this (with different names for the two symbols):
} catch (err) {
error(err);
}
So, when you try to call error(error)
you're trying to execute a non-function which throws which causes onAdd()
to reject the promise that the async function returns and you don't have a .catch()
handler on that function call (because you didn't think it could reject). And, as long as your catch()
handler is written so that it doesn't throw itself, then your promise won't reject, but your coding error was causing it to throw.
Upvotes: 4
Reputation: 1586
The method that calls this function should handle the error too, probably on your React Class
Upvotes: -1