I'm having trouble getting Apollo's useQuery to work properly. Are there any ways to enable debug statements or other tools for troubleshooting the Apollo client?

Setting up the Apollo client according to the documentation, I have configured the ApolloProvider to enable the use of useQuery in nested components. Running queries using the provided apolloClient within the ApolloProvider works without any issues. However, further down the component hierarchy, a similar setup is not yielding the expected results.

export default function SomeScreen({ route }: RouteProps) {
  ...
  let query: DocumentNode;
  switch (route.params.someParam) {
    case 'A':
      query = someQuery1;
      break;
    ...
    default:
      query = someQueryX;
  }

  const {loading, error, data} = useQuery<{myData: SomeType[]}, QueryArgTypes>(
    query,
    {variables}, //assigned elsewhere but they're constant
  );

  if (loading) return <Text>Loading</Text>
  if (error) return <Text>Error</Text>
  return (
    <FlatList
      data={data?.myData}
      renderItem={({ item }) => (<SomeComp elem={item} />)}
      keyExtractor={(item) => (
        item._id!.toString()
      )}
    />
  );
}

The issue arises when the if (loading) condition always evaluates to true. Even with breakpoints set within the apolloClient.query() execution, the query does not seem to reach the backend at all. The URI used during the apolloClient instantiation belongs to the project itself, ruling out external conflicts. Despite troubleshooting, it appears that the useQuery hook fails to execute the query successfully.

If anyone has encountered a similar problem or has insights into potential solutions, your input would be greatly appreciated. Notable dependencies include:

"react": "17.0.1",
"react-native": "0.64.3",
"@apollo/client": "^3.6.2",

Answer №1

Unfortunately, I'm not certain about the exact nature of that problem, but here is a sample code snippet to ensure that your client setup is correct:

client.js

const httpLink = createHttpLink({
  uri: URL_GRAPHQL,
});

const authLink = setContext( async (_, { headers })  => {

  const token = await getTokenService()
    
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : "",
    }
  }
});

const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache()
});


export default client

App.tsx

import React from 'react';
import { StatusBar } from 'react-native';
import { ApolloProvider } from '@apollo/client';

import AppRouter from './src/routes/AppRouter';
import client from './src/graphql/client';

export default function App() {

  return (
                
    <ApolloProvider client={client}>
      
      <StatusBar barStyle='light-content'/>
      <AppRouter />
      
    </ApolloProvider>
    
    
  );
  
}

Child component:

const ListScreen : React.FC<IProps> = ( { route } ) => {
  
  let listId                              = route.params.listId;
  const styles                            = useStyles()
  const { loading, error, data, refetch } = useQuery<ListResponse>(GET_LIST_ById, { variables: { listId } });
  
  return (
     <view>
     </view>
  )
  
  }

Answer №2

It turns out there was a known issue with this. If you're experiencing the same problem, I found a solution by updating to the beta version:

'loading' stays true while fetching data with 'useQuery' using 'apolloClient' in react-native

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

Creating a .d.ts file for a JavaScript file that exports a plain object - tips and best practices

I am attempting to include a .d.ts file for an existing js file. The type.js file looks like this: // type.js export default { NORMAL: '001', CHECK: '002', }; Now, I have added a type.d.ts file as follows: // type.d.ts decla ...

Backdrop dimming the Material UI Modal

My modal is designed to display the status of a transaction on my website, but I'm facing an issue where the backdrop dimming effect is being applied over the modal. Instead of appearing white as intended, the modal ends up having a dark gray tint. I ...

Encountered a new problem post code refactoring: "Error with prop validation: prop failed type check"

Currently, I am developing an application using Vue.js 2 with Typescript and utilizing the vue-property-decorator attributes. Recently, I made the decision to refactor a majority of my code which has resulted in encountering errors whenever I pass a binded ...

Created computed getter and setter for Vue models (also known as "props") using the syntax of Vue Class Component

After exploring the limitations of v-model in Vue 2.x in this Stack Overflow thread, I discovered a way to connect parent and child components using v-model. The solution proposed is as follows: --- ParentTemplate: <Child v-model="formData"> ...

Merge the values of checkboxes into a single variable

How can I gather all the checkbox values from my list and combine them into a single variable? This is the structure of my HTML: <div class="card" *ngFor="let event of testcases" > <input class="form-check-input" ...

Component coding in Angular 2 allows for seamless integration and customization of Material

I am looking to initiate the start.toggle() function (associated with Angular 2 material md-sidenav-layout component) when the test() method is triggered. How can I execute md-sidenav-layout's start.toggle() in the app.component.ts file? app.componen ...

Is it permissible to incorporate a snackbar within my service?

I am trying to retrieve error details from a service call that communicates with an API in case of an error occurrence. For example, if the HTTP error returned is 422, I want to display a user-friendly message. Below is my service class: @Injectable() e ...

Optimal approach for designing interfaces

I have a situation where I have an object retrieved from the database, which includes assignee and author ID properties that refer to user objects. As I transform a number into a user object, I am unsure about the best practice for defining the type of the ...

What is the procedure for incorporating nameless methods into TypeScript interfaces?

While working on a project involving graph visualization, I came across the following interface within the d3.js typings (original source can be found here): export interface Force<NodeDatum extends SimulationNodeDatum, LinkDatum extends SimulationLink ...

Do not include ChangeDetectionStrategy when creating component

Is it possible to eliminate the default ChangeDetectionStrategy for each component creation? (Please note that I am working with Angular V 10 in a controlled environment for project maintenance) @Component({ xyz, changeDetection: ChangeDetectionStrategy. ...

Verify registration by sending an email to an alternate email address through Angular Firebase

I have implemented email verification for users before registration. However, I would like to receive a verification email to my own email address in order to finalize the registration process. I want to be notified via email and only after my approval sho ...

Is it possible for me to make the default export anonymous?

Why bother naming the export if you already have a file with the default export name? This seems redundant and goes against the DRY principle. While there is a rule that discourages anonymous default exports, how can we enforce an error when someone does ...

Error message: Angular material StaticInjectorError - MatDialog provider not found

After trying to launch my Angular 5 page in the browser, I encountered an error message in the console. ERROR Error: StaticInjectorError(AppModule)[AppComponent -> MatDialog]: StaticInjectorError(Platform: core)[AppComponent -> MatDialog]: ...

Trigger a refresh of the BootStrap Modal with each key press event

Previous questions have addressed my issue, but the proposed solutions have not been effective for me. I attempted to split the component differently, but it still refreshes with each keypress. const TenementRegistration = () => { const [show, setSh ...

"Troubleshoot: Issue with React class component's setState not correctly updating

Hey there! I could really use some help with the issue I'm facing: So, I have a React class component that extends React.Component and it has a method that allows me to set its state whenever I want. I understand that passing a prop to the component ...

Response Looping Function

I am struggling with looping and storing data in an array. /** Model for displaying response*/ export class ResultsData { id: number, name: string, startDate: string, endDarte: string, startTime: string, ...

Compilation issues in node-modules arise following the Vue package and i18next updates

Recently, I decided to upgrade from the i18n package to the newer version called i18next in my project. However, this update led to numerous errors popping up during compilation. Fortunately, by adding 'skipLibCheck' to the compiler options in th ...

typescript error in navigating with parameters

Having trouble adding a param with TypeScript and encountering the following error: Error: Argument of type '["Profile", { screen: Screen; }]' is not assignable to parameter of type '[screen: "Explore"] | [screen: "E ...

Implementing a header and bottom tabs overlay in a react native application

Is it possible to display a view overlay on top of the header and bottom tabs in a react native app? The bottom tabs and header are created using createBottomTabNavigator. I have tried using position absolute in a view with all positions set to 0. I do n ...

Angular's ng serve is experiencing issues with mark-compacts near the heap limit, leading to an unsuccessful allocation

Encountering an issue while running ng serve in my Angular project. However, ng build --prod seems to be working fine. <--- Last few GCs ---> [4916:00000276B1C57010] 588109 ms: Scavenge (reduce) 8180.7 (8204.3) -> 8180.6 (8205.1) MB, 3 ...