I'm struggling to create a similar query in GraphQL because I can't quite grasp how to execute it

I am currently developing a car rental application as a personal project. Within the /vehicles route, there are lists of available vehicles. I have included 5 select inputs on the left sidebar for filtering purposes. My goal is to apply a filter when a value is selected and remove it when no value is selected. I am struggling with deciding how to properly structure the query and data transmission process. Can anyone offer assistance?

subscription Vehicles($daily_price: String) {
      vehicles(where: { _or: { daily_price: $daily_price, fuel: {}, gear: {}, model_id: {}, brand_id: {} } }) {
        id
        fuel
    }
const { data, loading, error } = useSubscription(from && to ? VEHICLES_BY_DATE_RANGE : VEH_SUBS, {
      variables: {
         ...filters,
      },
   });

Answer №1

Here is an example of how to handle variables in your code. The type declarations are based on my assumptions from your snippets, so you may need to make adjustments.

// For brevity, I'm omitting the definition of Where filters and focusing on the query:
const VEH_SUBS = gql`
  subscription getVehicles($where: Where!) {
    vehicles(where: $where) {
      model {
        name
      }
    }
  }`;

// Assuming filter types based on your snippets (e.g. brand_id could be a number).
const createQuery = (filters: { brand_id?: string, fuel?: string, }) => {
  const filterConditions: {
    where: { _or: { brand_id?: { _eq?: string }, fuel?: { _eq?: string } } }
  } = { where: { _or: {} } };

  // Setting up filterConditions for brand_id and fuel.
  if (filters?.brand_id) filterConditions.where._or.brand_id = { _eq: filters.brand_id };
  if (filters?.fuel) filterConditions.where._or.fuel = { _eq: filters.fuel };

  const { data: d, loading: l, error: e } = useSubscription(
    VEH_SUBS, // This should be a query that accepts 'where' as an argument!
    { variables: {where: filterConditions }}
  );
  ...
};

I suggest using graphql-codegen to generate types instead of assuming them like I have done, and avoiding the use of any.

Answer №2

Apologies for the confusion in my earlier explanation of the issue at hand. Here's how I managed to resolve it, which might provide you with a clearer understanding:

function generateQuery(filterData: any) {
      const conditions = [];

      if (filterData?.category_id) conditions.push(`category_id : {_eq: "${filterData.category_id}"}`);
      if (filterData?.type) conditions.push(`type: {_eq: "${filterData.type}"}`);
      let query;
      if (conditions.length > 0) {
         query = `
            {
               _or: {${conditions.join(", ")}}
            }
         `;
      } else query = "{}";

      return gql`
            subscription fetchResults {
               results(where: ${query}) {
                  details {
                     description
                  }
               }
            }
         `;
   };

   const query = generateQuery(filterData);

   const { result: data, isLoading: loading, error: err } = useSubscription(query);

I sincerely appreciate your efforts and interest. However, it would be extremely helpful if you could grasp the problem and suggest an alternative solution.

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

Ways to showcase the refined object array upon clicking a button in Angular

I have been working on a project to create a task management system. The project consists of two main components: itemList and item. The itemList component takes input values for tasks and displays them in the item component. https://i.sstatic.net/SaRNMm. ...

Unresolved issue with RxJS - Finalize not triggering

When attempting a logout request, I have encountered an issue where the same actions need to be dispatched regardless of whether the request is successful or fails. My initial plan was to utilize the finalize() operator for this purpose. Unfortunately, I ...

In TypeScript, at what level should the timeout be specified?

I'm currently working on writing a debounce function in TypeScript, but I'm feeling uncertain about the type that should be assigned to a variable used with setTimeout. This is the snippet of my code: function debounced(func: () => void, wait ...

The next.js docker error I encountered was related to getServerSideProps, showing a connection error with code "connect ECONNREFUSED 172.25.0.2

I have two separate docker-compose.yaml files. One is for the backend which includes its database, nginx, and node.js, while the other one is for my Next.js frontend application. FRONTEND: services: bsb_front: image: bsb_front container_name: b ...

Cannot locate AngularJS + Typescript controller

I'm encountering an error while attempting to integrate TypeScript with AngularJS. The issue I'm facing is: Error: [$controller:ctrlreg] The controller named 'MyController' has not been registered Does anyone have any insights on what ...

Issue: App(...) is not rendering anything. This typically indicates that a return statement is missing in discord.js using react and typescript

I am struggling with an error while working on Discord OAuth2, Typescript, and React. I have tried to troubleshoot it myself but couldn't find a solution. Can someone please assist me? The issue involves being redirected constantly to the entered addr ...

The Azure DevOps pipeline is programmed to generate Personal Access Tokens (PAT) and halt

I've been working on deploying my NextJS application to Azure Web Service using Azure DevOps. I have set up an automated deployment pipeline that looks like this: trigger: - main pool: vmImage: ubuntu-latest name: $(Build.DefinitionName)_$(Bui ...

Encountering a node-sass error while attempting to build due to upgrading node version

Currently, I am working on a Node v10.19.0 / Nextjs8 project locally and looking to upgrade to Next version 11. To begin the process, I decided to update the node version itself to 12.14.0 (or maybe 12.20.1?). However, this led to encountering 2 errors: &g ...

Top method for extracting a correlation matrix using an API endpoint

I am currently storing correlations on Google Firebase in a structure that resembles the following: {a: {a: 1.0, b: 0.6, c: -0.3, ...}, b: {a: 0.6, b: 1.0, c: -0.5, ...}, ...} My goal is to efficiently retrieve a complete correlation matrix while also hav ...

Angular's mechanism for detecting changes in a callback function for updates

I have come across a puzzling scenario regarding a basic issue. The situation involves a simple component with a boolean property that is displayed in the template of the component. When I update this property within a callback function, the property is up ...

What could be causing the global npm package to not be utilized for module dependencies?

My typescript and ts-node are already installed globally. In my package.json file, I have the necessary configurations to run tests with npm test. Everything works fine since ts-node and typescript are installed as local modules. { "name": "two_sum", ...

Managing the outcome of numerous asynchronous calls before accessing the database post-result collection

Hey everyone, I'm just getting started with node.js and I'm working on the following tasks: Calling the AWS API to create Cognito users by passing data. After all requests are completed, inserting all the records into the database. In my code, ...

Variations in comparing tuple types in TypeScript

Exploring the TypeScript Challenge, there is a particular problem known as IsNever. The task at hand is to create a type called IsNever that takes input of type T. If the resolved type equates to never, the output should be true; otherwise, it should be fa ...

Craft fresh items within HTTP request mapping

I am currently working on a function that subscribes to a search api. Within the map function, my goal is to transform items into objects. I haven't encountered any errors in my code, but the response always turns out empty. Here's the snippet o ...

Switch the ngClass on the appropriate ancestor element for the dropdown menu

Utilizing Angular CLI version 8.3.0, I aim to construct a sidebar featuring a drop-down menu. My objective is to apply the "open" class to toggle the opening of the drop-down section. However, the current challenge I am encountering is that when I click to ...

The Angular2 view is failing to display updated data from a shared service

I've been struggling to show data from my shared service, but it's not displaying. Can someone please help me out? I've been stuck on this for the past few days. I've tried NgZone and ChangeDetectorRef, but they haven't worked for ...

Troubleshooting: Models Not Loading in Next.js with Sequelize

I have generated numerous files using the sequelize CLI following their documentation available here: documentation link. Both the pages and db directories are located in the project's root directory. The content of my /pages/api/login.js file is as ...

Updating the status of a parent state in a functional component with React is a common task. Here

I'm currently working with two useState hooks in my code. When the status of the second useState is true, I want to set the status of the first useState to false. While I've been able to achieve this using class components, I'm unsure how t ...

Tsc encounters issues when interacting with AWS services

When attempting to compile TypeScript code into JavaScript using tsc, I encountered constant crashes specifically related to AWS code within the node_modules directory. Despite my efforts to resolve the issue by adding skipLibCheck to my tsconfig file, inc ...

Adding data-attributes to a Checkbox component using inputProps in React

Utilizing Fabric components in React + Typescript has been a breeze for me. I have been able to easily add custom attributes like data-id to the Checkbox component, as documented here: https://developer.microsoft.com/en-us/fabric#/components/checkbox Howe ...