In my React Native app I make an API call and then try to apply the json() method to the result, like this:
await fetch(...)
.catch(e => {...})
.then(res => res.json().then(...)
Typescript throws a warning on json() saying Property 'json' does not exist on type 'void | Response'.
What I Want To Know:
- Is there a way to prevent this warning?
- If I swap the order of
catchandthen, the error goes away. But I wantcatchto catch only errors fromfetch(), not from the code in thethenblock. Is there a way to achieve this?
>Solution :
Use optional chaining:
await fetch(...)
.catch(e => {...})
.then(res => res?.json?.().then(...)
The optional chaining operator (
?.) enables you to read the value of a
property located deep within a chain of connected objects without
having to check that each reference in the chain is valid.