Execute a graphql query within the fetch function

Need help with calling a GraphQL query within the fetch method. Can anyone guide me on how to achieve this?

Specifically, I need to execute the following query inside the fetch method:

query AddressList($street:String, $city:String, $state:String, $zip:String) {
   address_list(street:$street, city:$city, state:$state, zip:$zip){
    street
    city
    state
    zip
    
  }
}

If you have any suggestions or solutions, please do share them. Thank you.

Answer №1

I found a useful snippet to simplify GraphQL requests:

    async function graphql(query, variables={}){
        const response = await fetch('/graphql', {
            method:"POST",
            headers: {
                "Content-Type": "application/json"
            },
            body:JSON.stringify({
                query,
                variables
            })
        });
        var result = (await response.json());

        // error handling
        if(result.errors){
            throw result.errors
            
        }
        
        if(response.ok){
            return result.data
        }
        
        throw result;
    }

You can use it like this:

const { address_list } = await graphql(`query AddressList($street:String, $city:String, $state:String, $zip:String) {
   address_list(street:$street, city:$city, state:$state, zip:$zip){
    street
    city
    state
    zip
    
  }
}`,{street:'123 Street',city: 'Example City', state:'Sample State'})

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

Guide for implementing express middleware at the router level

I am currently attempting to implement a basic middleware function that will run for every request at the router level. According to the documentation: a middleware function with no mount path will be executed for every request to the router In my appl ...

Revamping Cookie-based sessions in express.js

I am currently utilizing the cookie-session module for Express.js to manage sessions. My goal is to refresh sessions on each page load or ajax call, as is typically seen in similar setups. Unfortunately, the documentation lacks any information regarding ...

Issue with Node.js: Unable to locate address using getaddrinfo

I'm currently working on a node application that needs to make https requests to an external URL. However, I'm facing some challenges due to being behind a corporate proxy. I have already configured the proxy settings as shown below: >npm con ...

Node.js/NPM issue on Windows machine

I've encountered a situation where all npm commands are getting stuck indefinitely, no matter how long I wait. This issue seems to occur after using npm for a while. Currently, the only solution I have is to restart my PC (yes, resorting to Windows f ...

Can you explain the inner workings of the provided code in a step-by-step manner?

I stumbled upon this code snippet that checks if the number of occurrences of an element in an array is greater than a specified value, and if so, it will remove the number: function deleteNth(arr,x) { var cache = {}; return arr.filter(function(n) { ...

How can audio be efficiently streamed to the browser in small chunks using JavaScript?

I am currently working on setting up an internet radio station where I want to easily switch songs and overlay sounds. My goal is to limit the audio rate so that the feed can be adjusted before being sent out. Additionally, I would like to provide continuo ...

Create multiple package-lock.json files with a suffix for backup purposes

I've observed that npm generates multiple package-lock*.json files in the main directory of my project. I'm uncertain about the purpose of these files and why there are so many being created. Attached is an image displaying the generated files. ...

When querying for a specific document in mongoose using findById,

I am currently working on a task management application where I have encountered an issue. When trying to move a task from the to-do list to the done list, the methods "columnId" and "findById" are returning null values. Can you offer any insight into wh ...

Executing a Python script through Node.js and storing the output as a file

Despite being able to successfully run a python script, I am facing challenges when it comes to saving a file using the script. While running the python script directly from the terminal yields positive results, spawning a node process seems to fail withou ...

Why does the Amazon DynamoDB scan trigger an error by making two HTTP requests to the server?

My TypeScript React application is using DynamoDB services to store data, with a JavaScript middleware handling the database access operations. While developing locally, I successfully implemented the scan, put, and delete operations with no errors. Howeve ...

Unleashing the Potential of a Single Node Express Server: Hosting Dual Angular Apps with Distinct Path

I have successfully managed to host two separate angular applications (one for customers and one for company staff) on the same node server, under different paths. The setup looks like this: // Serve admin app app.use(express.static(path.resolve(__dirname, ...

I am facing issues with getting create-react-app to function properly on my computer

While attempting to start my React project, an error log appeared C:\Users\Ezhil & rishii>npx create-react-app firstapp 'rishii\AppData\Roaming\npm\' is not recognized as an internal or external command, opera ...

AWS Lambda, where the billing time exceeds the actual processing time

While working on my Lambda function in Node.js, I noticed a significant difference in the time measured from the start to the end of the function compared to the billed duration provided by Lambda. The function itself takes around 1400 milliseconds to exec ...

Guide on importing an external JavaScript library in Node.js utilizing a TypeScript declaration file

I am working on a Node.js project using Typescript and I am facing an issue with integrating mime.js (https://github.com/broofa/node-mime). Even though I have a declaration file available (https://github.com/borisyankov/DefinitelyTyped/blob/master/mime/mim ...

What is the reason that the 400 status code consistently causes the enter catch block to execute when using axios?

In the frontend of my website, there is a contact form with three fields -> name, email, message. These fields are then sent to the backend using Axios. If a user fails to fill out any of the required fields, they should see a message saying "please f ...

Retrieve the information following a redirection

There is a page '/order/new' with 2 dropdown menus for customer and their address, along with a button that redirects to choose products to add to the order. The selected products are saved in an array called 'hh' which receives data fr ...

Is there a way to ensure that the line numbers displayed for JavaScript errors in Chrome are accurate?

I suspect either my webpack configuration or my npm run dev script are causing the issue, but I'm unsure of what exactly is going wrong. While running my application in development mode, I encounter error messages like: Uncaught TypeError: this.props ...

When Selenium in JavaScript cannot locate a button element, use `console.log("text")` instead

I am trying to capture the error when there is no button element available by using console.log("No element"). However, my code is not working as expected. const {Builder, By} = require("selenium-webdriver"); let driver = new Builder().forBrowser("chrome ...

Troubleshooting npm faq on Windows 7: How to handle 'spawn ENOENT' errors

After installing node.js on my Windows 7 using the latest installer, I encountered some issues. While I am able to call npm and node from the console (cmd or PowerShell), errors keep popping up. I have noticed many discussions about node.js on windows, bu ...

Troubleshooting CSS pathing problem in Node.js web app hosted on A2 Hosting

I am currently learning node.js and still relatively new to it. Please excuse me if my first question is inefficient or poorly formatted. I am trying to upload a one-page test to explore A2's node.js service. Following tutorials from A2 on creating a ...