Tips for catching errors in Apollo Client while executing GraphQL queries

Here is my approach to querying data from a Graphql engine.

export GraphQLWrap <TData, TParam = {}>({
  query,
  extractData,
  children,
  queryVariables,
  skip,
}: AsyncWrapProps<TData, TParam>) => {
  return (
    <ApolloConsumer>
      {client => {
        const loadOptions = (
          searchString: string,
        ): Promise<SelectOptionType[]> =>
          skip
            ? Promise.resolve([])
            : client
                .query<
                  TData,
                  | AsyncSearchVars
                  | (AsyncSearchVars & TParam)
                >({
                  query,
                  variables: {
                    search: `${searchString || ""}%`,
                    ...queryVariables,
                  },
                })
                .then(extractData);
        return <div>{children(loadOptions)}</div>;
      }}
    </ApolloConsumer>
  );
};

I have included this code snippet for handling Graphql queries. Any suggestions on how I can enhance it to handle potential GraphQL errors would be greatly appreciated. Thank you.

This is the method I use to interact with the component above:

const extractData = ({ data }: ApolloResult<AccountData>) =>
  data && data.vitm_account ? data.vitm_account : [];

  return (
    <GraphQLWrap query={ACC_NAME_QUERY} extractData={extractData}>
      {accountSelect}
    </GraphQLWrap>
  );

Answer №1

const setErrorHandler = useContext(ErrorContext);

  const handleAppErrors = (error: ApolloError) => {
    setErrorHandler(error);
    return [];
  };

  return (
    <ApolloConsumer>
      {client => {
        const fetchOptions = (
          searchInput: string,
        ): Promise<SelectOptionType[]> =>
          skip
            ? Promise.resolve([])
            : client
                .query<
                  TData,
                  | AsyncSelectSearchVariables
                  | (AsyncSelectSearchVariables & TParam)
                >({
                  query,
                  variables: {
                    search: `${searchInput || ""}%`,
                    ...queryVariables,
                  },
                })
                .then(getExtractedData)
                .catch(handleAppErrors);
        return <div>{children(fetchOptions)}</div>;
      }}
    </ApolloConsumer>
  );
};

We have the ability to utilize .catch method in order to pass any encountered errors to the handleError function.

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

Encountering an unusual issue: Unable to access undefined properties (specifically 'get')

I'm struggling to get the order history screen to display the order history of a specific user. Every time I navigate to the path, I encounter the error mentioned in the title. I double-checked the path for accuracy and made sure there are no spelling ...

IDE cannot find imported modules even though the NPM Package is functioning correctly

Working with npm has been a great experience for me, and my first package is functioning perfectly. However, in my IDE (Webstorm), when I import my package, it shows a "Cannot resolve symbol" error (even though it works). Furthermore, when I use ...

Version 5 of Material UI has a bug where the Grid component does not properly stretch

How can I make the Grid component stretch when one of the Card components contains extra text? You can view the sample code here. Changing the alignItems property to "flex-end" or "center" works, but when using alignItems: "stretch" it does not work. I ...

I'm having an issue with Material UI v5 cardMedia images not displaying correctly on my live

I have a function that maps an array of objects in order to display a series of MUI cards utilizing the "cardMedia" component. The images are displaying properly on my local host, but once I deployed the code to Netlify, the images appear broken. Here is ...

What is the best way to retrieve the values of all the keys in Firebase Realtime Database?

At first, I only retrieved the values associated with each key. However, upon further reflection, I realized that I actually need to obtain the keys themselves and then access the corresponding values. I have now commented out my previous approach. https: ...

What is the reason behind the warning "Function components cannot be given refs" when using a custom input component?

When attempting to customize the input component using MUI's InputUnstyled component (or any other unstyled component like SwitchUnstyled, SelectUnstyled, etc.), a warning is triggered Warning: Function components cannot be given refs. Attempts to acc ...

Managing data flow in React and Reflux: Utilizing a single component duplicated in the DOM

Imagine this Tree scenario: <Homepage> <HeaderSection> <Navbar> <ShoppingCartComponent> </Navbar> </HeaderSection> <MainContent> <ShoppingCartComponent> &l ...

What steps can I take to avoid encountering the `@typescript-eslint/unbound-method` error while utilizing the `useFormikContent()` function?

Recently, I updated some of the @typescript-eslint modules to their latest versions: "@typescript-eslint/eslint-plugin": "3.4.0", "@typescript-eslint/parser": "3.4.0", After the update, I started encountering the fo ...

Using React's useEffect and useContext can cause issues with certain components, particularly when dealing with dynamic routes

Currently, I am developing a React blog application where posts are stored in markdown files along with metadata in Firestore. The content .md files are saved in Cloud Storage. In the App component, I utilize useEffect to retrieve the metadata for each pos ...

Using Mapbox's geocoder with React

After creating my first React app, I decided to upgrade the d3 map to a more modern Mapbox version. The data being transmitted consists of country names and their respective percentages, with the goal of visualizing each country along with its percentage ...

Steps to incorporate multiple line selections in a select dropdown using Material UI

I am trying to create a Material UI Select where the options (MenuItem's) can accommodate long texts. For example, here is what one option may look like: "A new building or one that has undergone a major renovation within the last two years, which on ...

Establishing the default scroll position in tables using React.js

How can I set the initial scroll in ReactJS Material-UI tables? I'm working with a table that has numerous columns and I would like to have specific columns in view automatically without having to scroll, essentially establishing an initial scroll. I ...

Front-end displaying empty data fields on my webpage

I've been struggling to understand why my data isn't mapping correctly on these two components. I have attempted two debugging methods to analyze my code and have observed the data object for both the navigation and footer. Unable to comprehend ...

Stylis-plugin-rtl for Material-UI V5 ensures that your application is fully compatible

I am using Material UI 5 with Next.js and have followed all the steps outlined in the documentation here, along with the Emotion and Stylis-plugin-rtl v2: However, after refreshing the page, my input label jumps to the left initially and then moves righ ...

Create a precise layout for a footer design

I recently revamped a footer using a new UI framework in an attempt to improve it. Despite my efforts to align it properly, I encountered issues with overlapping on the right side. I experimented with using <div> and applying styles to create a diffe ...

In ReactJs, what is the best way to load a new component when a button is clicked?

In ReactJs, I have developed a main component known as MainPage using Material-UI. import React from 'react'; import Grid from '@material-ui/core/Grid'; import Button from '@material-ui/core/Button'; import CssBaseline from & ...

Guide on how to add a file path reference into an HTML table

I am encountering an issue with internal links within HTML tables in Docusaurus. I need to showcase intricate tables that are not supported in standard markdown format, and include links to other pages inside table cells. For instance, an MDX file include ...

Customizing Material UI tooltip styles with inline CSS formatting

Currently in the process of creating a React component that utilizes the Material UI Tooltip feature. In my component, I have the need to manually reposition the Mui Tooltip by targeting the root popper element (MuiTooltip-popper). However, the Mui Toolti ...

What is the functionality of the Material-UI theme light and dark mode feature?

I am having trouble understanding how the light/dark feature in this theme operates. I have noticed that changing the main color affects the components, but adjusting the light/dark value in type does not seem to have any effect. const customizedTheme = ...

The React Bootstrap modal refuses to fully close no matter how many times I click away or even on the close button

I am facing an issue with a modal in my React component. When I open the modal, it does not completely close when I try to click away or hit the close button. The backdrop disappears but the modal itself remains on the screen. (Screenshots attached for r ...