How can we implement the json() method on a promise result that may be either a Response or void in Typescript?

When working on my React Native app, I encountered an issue with making an API call and using the json() method on the result. Here is the code snippet:

await fetch(...)
  .catch(e => {...})
  .then(res => res.json().then(...)

An error was thrown by TypeScript stating:

Property 'json' does not exist on type 'void | Response'
.

My Query:

  1. Is there a way to avoid this warning?
  2. I noticed that swapping the order of catch and then resolves the error. However, I only want catch to handle errors from fetch(), not from the code within the then block. Is there a workaround for this?

Answer №1

To simplify your code, consider utilizing optional chaining:

await fetch(...)
  .catch(e => {...})
  .then(res => res?.json?.().then(...))

By using the optional chaining operator (?.), you can access nested property values without needing to validate every link in the chain.

Answer №2

When I switch the positions of catch and then, the error disappears. However, my intention is for catch to only handle errors that arise from fetch(), not from the code within the then block. Is there a way to accomplish this?

A solution would be to utilize .then(…, …) instead of .then(…).catch(…):

await fetch(...).then(res =>
  res.json().then(…)
, e => {
  …
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to modify data with ionic and firebase in child node format

I am encountering an issue when updating data with Ionic Firebase using the following code. Instead of rewriting the previous data, it simply creates new data entries. Here is the code snippet: updateLaporan() { this.id =this.fire.auth.cur ...

What is the best way to access automatically generated JavaScript variables in TypeScript?

I am currently facing an issue with integrating a Google login API in my React project and I need some help. The problem arises when the user already has an active session, rendering the API unnecessary. The Javascript solution provided is as follows: co ...

Trouble accessing properties in Mongoose objects?

I am facing a puzzling issue while attempting to retrieve properties from a MongoDB (mongoose) find query. When I log the entire object, everything is visible. However, when I attempt to access a specific property, it returns undefined. The object is cert ...

Guide to indicating the chosen filter in React using Material UI

I'm currently working on a blog that includes a filter feature. The filtering functionality is working perfectly, but I am trying to specify which filter option is currently selected. Here is the code snippet: {cardCategories.map((cat) => { retu ...

Tips for linking my TypeScript document to the server

Recently diving into the world of Angular 2 and seeking to grasp its intricacies. Currently utilizing Visual Studio Code. How can I have the server monitor changes in the TypeScript file? Do I need a compiler to convert it to JavaScript for this purpose? ...

Creating a visual comparison by using knockout side by side

I'm currently working on a project that requires me to display multiple items side by side for comparison. The ideal layout would be similar to Amazon's, where each item is represented by a vertical column with all relevant information about tha ...

Adjust the field of view of the camera in ThreeJS

I'm currently working on adjusting the field of vision for a camera without having to create a new one. So far, I've successfully achieved this for the position using the following code: camera.position.set() Now, I'd like to implement a s ...

Enabling cookie functionality for a component in React.js

I recently came across an article discussing how to set cookies in React code without using any libraries. The article provided some insights into the process, but I wanted to implement a welcome box for first-time visitors using just JavaScript. I tried c ...

Creating interfaces within props is essential for defining the structure of components

I'm trying to pass an Interface to one of my components, but I'm running into some issues with my approach. Here's what I have so far: import { InterfaceType } from "typescript"; type Props = { dataType: InterfaceType } export default ...

Tips for enhancing a search algorithm

I am currently working on implementing 4 dropdown multi-select filters in a row. My goal is to render these filters and update a new array with every selected option. Additionally, I need to toggle the 'selected' property in the current array of ...

What could be causing the issue with the is condition in my Yup validation?

Currently, I am tackling a TypeScript project that involves utilizing Yup for form validation. My current roadblock pertains to a hiccup with the when function and the is condition. TypeScript is raising an error (TS2769) related to types, and I am struggl ...

What could be causing my redux-observable to not be triggered as expected?

Currently diving into the world of RxJS and Redux Observables within Redux, attempting to grasp the concepts by implementing a basic fetch example. This is how I've configured my store: import { applyMiddleware, createStore } from 'redux' ...

Having trouble displaying a set of data points in a React component

Exploring React, I have built a test app and performed an API call to fetch a large JSON object. After breaking it down into 10 arrays with 3 props each, I am now facing a challenge in sending this data to another component. Despite being able to log the ...

Node.js is the perfect platform for streaming videos effortlessly

I'm attempting to live stream a video from my server, but it seems like I may be doing something wrong: Here is how my routes are defined: var fs = require('fs'); router.get('/', function(req, res) { fs.readdir(__dirname + &ap ...

Similar to Angular ui-router 1.0.3, what is the equivalent function for reloadOn

After updating to UI-router v1.0.3 from v0.3.2, I noticed that the reloadOnSearch feature has been removed from the stateConfig. I'm having trouble finding the equivalent of reloadOnSearch in v1.0.3. It doesn't seem to be documented anywhere. A ...

Getting row data from ag-grid using the angular material menu is a straightforward process

I have a specific requirement in ag-grid where I need to implement a menu to add/edit/delete row data. Currently, I am using the angular material menu component as the cell template URL. However, I am facing an issue where when I click on the menu item, it ...

What is the process for incorporating the QuillJS module into a component in Angular 2?

As a newcomer to Angular 2 and TypeScript, I have been utilizing AngularCLI and NPM to set up my Angular Project. Recently, I installed the Quill node module using NPM for project integration. Now, I am in the process of developing a component where I can ...

How to send varying URL parameters to AJAX function within Django applications

Can anyone assist with passing different URL names to a javascript function? Below is the HTML and Javascript code I am using: {% for profile, g_name in group_list %} <li class="contact"> <div class="wrap"> ...

What could be causing JSON.parse to encounter errors when parsing a string array?

Within the following function, I am utilizing JSON.parse() on specific string arrays saved in window.sessionStorage. This allows me to apply methods like .map(). window.sessionStorage = { myArray1: "["805746|search|4","980093062|search|0","980113648| ...

Navigating TS errors when dealing with child components in Vue and Typescript

Recently, I encountered an issue where I created a custom class-based Vue component and wanted to access its methods and computed properties from a parent component. I found an example in the Vue Docs that seemed to address my problem (https://v2.vuejs.org ...