Examining for information using the fetch method

Utilizing the fetch method for API calls that provide JSON data.

Sometimes, the response from the API call includes a status of OK but with a content value of null. Initially, I relied on solely checking the status for content which led to errors when there was no actual JSON data present.

The error message I encountered is:

Uncaught (in promise) SyntaxError: Unexpected end of JSON input

My current fetch pattern requires adjustment to incorporate an additional check for the presence of JSON data. What modifications should be made?

export const getSomeData = () => {
    return (dispatch) => fetch('/api/myapifunction', fetchOptionsGet())
        .then((response) => {
            if(response.ok) {
                // Additional logic needed here to verify JSON data before calling parseJSON
                parseJSON(response)
                .then(data => {
                    // Perform desired actions
                })
            } else {
                // Request failed
                // Error handling
            }
        })
}

I have implemented separate functions like fetch options for GET or POST requests and parseJSON. These are basic utility functions. Here is how parseJSON function is defined:

export const parseJSON = (response) => {
    return response.json();
}

It appears that response.json() simply returns a promise, not raw data. How can I validate the presence of JSON data in the response?

Answer №1

If the browser successfully interprets the response content as valid JSON, the response.json() promise will execute and move to the .then block.

If the browser is unable to parse the response content as JSON, you can utilize the .catch block to identify the issue:

parseJSON(response)
    .then(json => {
        // Perform actions using the json data
    }).catch( reason => {
        // The response does not contain a valid JSON string
    })

Answer №2

The key issue here lies in the deceptive behavior of your service. While it claims to be OK, it actually sends no data bytes at all, resulting in an error when parsing JSON.parse('').

To address this, you can either follow Dekel's suggestion and utilize a catch clause, or opt for response.text() instead:

if (response.ok) {
  response.text()
    .then(text => text && text.length ? response.json() : Promise.resolve({}))
    .then(data => { // ensure proper handling of an empty object

This approach examines the content of the returned string. If nothing is retrieved, it will provide an empty object rather than triggering an error. This method helps distinguish between a JSON parse error due to faulty data and a situation where no data is returned.

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

Display the full price when no discount is available, but only reveal the discounted price when Vue.js is present

In my collection of objects, each item is structured like this: orders : [ { id: 1, image: require("./assets/imgs/product1.png"), originalPrice: 40, discountPrice: "", buyBtn: require(&q ...

The problem with escaping characters in Javascript occurs when a backslash is duplicated within an object

My intention was to save the JSON object with an escape character by escaping "/". I achieved this by using string replace to convert my string into "\/". Afterwards, I assigned this to an object variable and attempted to console log it, only to find ...

Tips for generating an HTML template as a string using jQuery

I have developed a dynamic modal using plain JavaScript, triggered by a button click. This modal is controlled based on the attributes `data-open-hours` and `data-closed-hours` in the HTML. If you take a look at my demo, you will notice an issue. Let me e ...

Changing the key name for each element in an array using ng-repeat: a guide

In my current project, I have an array of objects that I am displaying in a table using the ng-repeat directive. <table> <thead> <tr> <th ng-repeat="col in columnHeaders">{{col}}</th> //['Name&apo ...

Executing functions on Angular scope within Underscore Template

Having an underscore template being invoked from an Angular controller, there is a dropdown in the template and an onchange function called on the dropdown. Despite several attempts to get the method triggered in the onchange event, using this code <se ...

Updating the material-ui checkbox state to reflect the checked, unchecked, or indeterminate status, can be achieved in reactjs without relying on state

I am currently using Material-UI checkbox components and I have a requirement to programmatically change the state of checkboxes to be checked, unchecked, or indeterminate based on the click of another checkbox. This action needs to be applied to a list of ...

Using CSS to design a table-like structure with rows that span multiple columns

I am trying to generate a table dynamically using CSS and a JSON array. For example: In the code snippet provided, I have assigned a class of 'spannedrow' to span certain cells in the table, although the class is not defined yet. This is just ...

Guide to configuring Swagger UI to accept a request body with an optional field

Understanding the title is straightforward, but let's dive into the specifics: I've developed an expressjs application using TypeScript. When the app receives a request, the JSON body is structured like this: { name: "name", de ...

The responsive menu refuses to appear

my code is located below Link to my CodePen project I'm specifically focusing on the mobile view of the website. Please resize your screen until you see the layout that I'm referring to. I suspect there might be an issue with my JavaScript cod ...

Executing ForceAtlas2 algorithm from a predetermined starting point within Sigma.js

I need assistance with rendering a complex network using the React-Sigma wrapper. The base structure of this network consists of numerous nodes of degree one and some nodes with high degrees. I have prepared my graph data with x and y coordinates that repr ...

include a new value to the current state array within a react component

I am working with an array in React State and I need to add a new property called Value. However, every time I try to add it, it creates a new item in the array. What I actually want is for the new property to be added as follows: value: '' Belo ...

Tips for fetching data from a database using AJAX when the values of two drop-down lists are involved

I have successfully implemented an Example where I retrieve data using a single drop-down list from a database. Now, I want to extend this functionality to work with two drop-down lists, where the values retrieved from the database are dependent on the sel ...

Is it possible to incorporate an internal comment in Jira using JSON?

Currently, my team is facing a challenge with workflow automation in our Jira Service Desk project. To transition an issue from Step 1 (Waiting for support) to Step 2 (In Progress), users are required to enter a comment after clicking the "In Progress" but ...

"Unexpected outcome: Angular's HTTP request for a JSON file yields an undefined

Learning Angular has been a challenging experience for me. I am currently working on reading a json file into a chart on my main app page to visualize temperature data from my PI. Despite trying various methods found online, I have not been successful so f ...

What is the best time to fetch the height of an element containing an image?

I am working on my web app and I want to implement a popup element that contains an <img> element. Typically, the image source is larger than necessary, so I resize it using CSS. However, before displaying the popup, I need to determine its outerHeig ...

Converting an array from JSON Schema into OWL ontology

My current challenge involves the mapping of an array defined in JSON Schema to OWL 2. Here is a basic example of a JSON Schema: { "properties": { "nm_prop": { "type": "array", "items": {"type": "number"} } } } The r ...

Implementing RESTful API functionality in Django - A complete guide

I am currently facing a challenge in integrating a REST API created with Django-rest framework into another Django web application. I am having trouble passing JSON data to the front-end and would greatly appreciate any assistance. Below are my relevant fi ...

How do I retrieve an index value from an array in GraphQL?

I am seeking a solution for obtaining the index of an array item that is not returned by downstream response. Let's consider my schema: schema: type Cart { items: [Item] } type Item { name: String index: Int } When the data comes in, it lo ...

Using Angular 5 to link date input to form field (reactive approach)

I'm encountering an issue with the input type date. I am trying to bind data from a component. Below is my field: <div class="col-md-6"> <label for="dateOfReport">Data zgłoszenia błędu:</label> <input type="date" formC ...

Using the map function twice in React Native causes a rendering issue

<View style={styles.card} > {store.crud.list.map(function(element, index){ return ( <View style={styles.wrapper}> {element.map(function(number, index){ return( ...