Saving received JSON data from fetch() API request into a variable

Just starting out with JS and currently working on a project involving retrieving data from an API using a JS Notebook.

I'm trying to create a function that can make API calls based on a given URL, and then execute that function twice. The objective is to extract JSON Data from the API calls and store them in variables (Alldocs1 and Alldocs2).

However, I'm having trouble storing the results of the function inside the variables. While I've encountered similar issues before, the main difference here is that the fetch() method is being called within the main function itself.

I'm able to retrieve the JSON from the CallAPI() function, but how do I go about saving the obtained JSON from the API calls into the two variables? Any advice would be greatly appreciated.

async function callAPI (url, data) {
  var result=0;
  const response = await fetch(url, {
    method: "POST",
    body: JSON.stringify(data),
    headers: {
      "Content-Type": "application/json"
    }
  }).then(function(response){return response.json();}).then(function(obj){console.log(obj);result=obj;}).catch(function(error){console.error("Something went wrong.");});

  return result;
}

//--------------------------API CALLS-------------------------------------//

//AllDocs:

var res_json=0;

alldocs1 = callAPI("/api/allDocs/", {
  "portal_type": [
    "Quality Control Declaration"
  ]
}
)

alldocs2 = callAPI("/api/allDocs/", {
  "portal_type": [
    "Defect Declaration Operation"
  ],
  "creation_date":"2022-08-22"
}
)

console.log(alldocs1); //RETURNS PROMISE NOT JSON
console.log(alldocs2);

Answer №1

Give this code a try:

import fetch from "node-fetch";

const data = await fetch(url, {
    method: "POST",
    body: JSON.stringify(payload),
    headers: {
      "Content-Type": "application/json"
    }
});

const response = JSON.parse(data);

console.log(response); // displays the JSON response

I hope this solution helps you with your query.

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

Converting JSON into a C# Class through Deserialization

My API call returns a JSON data array with approximately 500 items: [ [ 1571702400000, "8197.28000000", "8297.99000000", "8000.00000000", "8020.00000000", "346 ...

How can you start a jQuery script following a triumphant Ajax callback?

Having some trouble getting jQuery to execute after a successful Ajax response. Even though I have it in the success callback, it doesn't seem to be working as expected. I came across a potential solution here, but I'm having difficulty understan ...

Tips for minimizing redundant calls to a JavaScript function

Currently working on an app using php and js. I have a menu sidebar with various items, where clicking on an item loads the corresponding php file into the main container using jQuery's load function. However, there is a critical problem when loading ...

The state variable remains undefined even after integrating useEffect in a React.js component

Hello, I have a component within my React application that looks like this: import React, { useEffect, useState } from "react"; import AsyncSelect from "react-select/async"; import { ColourOption, colourOptions } from "./docs/data"; const App = () => ...

Adjust the content size to 100% based on the quantity of items in a row

I've been having a hard time creating an image gallery that adjusts its size automatically (width: 100%) based on the number of items it contains. For example, take a look at this gallery: http://codepen.io/anon/pen/eNMOEz .item { width: 75px; h ...

Parallel Execution Issue with RxJS Observable forkJoin

Struggling to understand why my requests aren't executing concurrently with the following code. As a newcomer to RxJS and observables, I would greatly appreciate any guidance on improving this snippet below. Essentially, I am fetching data from a REST ...

Enhancing ajax post requests made with vanilla javascript by incorporating variables

I have successfully implemented a post ajax request in vanilla Javascript, but I am facing an issue. I need to include a variable in form_data that will be sent to PHP. For instance, the variable apple = 1 is already part of form_data. Now, I also want to ...

Ways to hide the value from being shown

I have integrated jscolor (from jscolor) to allow users to pick a color with an input field. However, I am facing issues in styling it as I'm unable to remove the hex value of the selected color and couldn't find any relevant documentation on av ...

Utilizing Quarkus REST API, the implementation of Multi<String> and APPLICATION_JSON return type introduces an extra layer of wrapping to

I'm encountering an issue with my Quarkus-based Rest API where, despite providing a JSON response correctly, an extra array wrapper is added to the output. Is there a way to prevent this unwanted addition of array wrappers around the JSON? Here' ...

Guide on dynamically rendering a route in Next.js when a fresh blog post is uploaded without the need for executing the npm run build command

I've encountered an issue with my blog app developed in Next.js. When I add a new blog post to the database, the page does not render the new route automatically. I have to manually run npm run build to pre-render the new blog, otherwise, it continues ...

Populate the jsrender template with initial data

Is there a way to display a select option within a table? $('select').append($('<option>').text('single')); $('table').append($('#rowTmpl').render({name:'peter'})); th,td {border:1px soli ...

The combination of the card hover effect and the bootstrap modal creates complications

Hey there! I'm in the midst of crafting a webpage using Bootstrap and EJS. My aim is to craft a modal window that pops up when a specific button is clicked to display extra information, and upon clicking an X or "close" button, the modal should disapp ...

"Troubleshooting why React fails to update an array state

When I click the update name button, the state is not changing properly using setState. I want to update the persons variable and have it reflect in the DOM as well. Any ideas on how to achieve this? App.js import React, { Component } from "react"; impo ...

detecting user interactions with hyperlinks

Can links be intercepted in an Angular application to block specific URLs like YouTube links without adding custom attributes or elements? Is it possible to intercept all clicks on links within the scope of a particular controller's view without modi ...

Is it possible to transform this nested promise into a chain instead?

This situation is just a scenario | then (items) | then (items, actions) getItems() | getActions(for:items) | apply(actions -> items) :promise | :promise | model <= items | | :sync ...

Filtering by labels

I need to search for the label "1125" and if it is not found, I want to show an alert box. Here is my code: if (var id = $('mobilelabel_2:contains("1125")').attr('for');) { alert ("works"); } else { alert ("try again"); } ...

Tips for accessing elements other than the root element using this.$el

Within my template, the structure is as follows: <div v-show="showContent" class="content-block-body"> <div class="slider-pro"> <div class="sp-slides"> <slide v-for="block in subItems" ...

Using Chrome's tabs.executeScript() method with an included script file

I'm in the process of creating a basic Chrome extension, where I need to actively monitor the AJAX calls being made on the page. Here is the code snippet I have implemented to listen to AJAX calls: var isAjaxWorking = false; //timeout var timeout; ...

Using Vuetify to incorporate properties into v-list-group v-slot:activator template

Trying to create a menu similar to the expansion lists example in the Vuetify documentation. This menu utilizes the v-list-group and v-slot:activator components. Each child element has a list-item, making it easy to add a Vue Router link. However, the chal ...

After the checkbox is clicked, I must send a boolean value to the function through the input flag in AngularJS

<input class="bx--toggle" id="toggle-view" type="checkbox" ng-model="vm.monthView" ng-change="vm.getRelevantData()" ng-attr-data-modal-target="{{vm.alertForSaveAll ? '#add-save-all-alert-modal': 'undefined'}}"> Within this p ...