question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to handle loading and error state in a generic way?

See original GitHub issue

In react-apollo 2.x, I used to handle loading and error state in a generic way by encapsulating the <Query> component as follows:

import * as React from 'react';

import { Query } from 'react-apollo';
import { CenteredMessage } from './centered-message';

export const DefaultQuery = ({ query, variables = {}, children }) => (
    <Query query={query} variables={variables}>
        {({ loading, error, data, fetchMore, subscribeToMore }) => {
            if (loading) {
                return <CenteredMessage>Loading...</CenteredMessage>;
            }

            if (error) {
                return <CenteredMessage>{error.message}</CenteredMessage>;
            }

            return children({ data, fetchMore, subscribeToMore });
        }}
    </Query>
);

What would be the equivalent pattern with react-apollo-hooks? I started writing a component similar to the above, but it doesn’t feel right to reintroduce render props in a hooks world:

import React, { ReactNode } from 'react';

import { OperationVariables } from 'apollo-client';
import { DocumentNode } from 'graphql';
import { useQuery } from 'react-apollo-hooks';
import { CenteredMessage } from './centered-message';

export interface DefaultQueryProps {
    query: DocumentNode,
    variables: OperationVariables,
    children: ReactNode
}

export const DefaultQuery = ({ query, variables = {}, children }: DefaultQueryProps) => {
    const { data, error, loading } = useQuery(query);
    if (loading) {
        return <CenteredMessage>Loading...</CenteredMessage>;
    }

    if (error) {
        return <CenteredMessage>{error.message}</CenteredMessage>;
    }

    // TODO: include fetchMore and subscribeToMore when available
    // return children({ data, fetchMore, subscribeToMore });
    return children({ data });
};

Besides, the above pattern works well for a single query. How would you enhance it to handle multiple parallel queries? In the render props world, I used to nest <DefaultQuery> components to achieve that, but its not very elegant. See my example here - it uses a triple-nested <DefaultQuery>.

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Reactions:4
  • Comments:12 (11 by maintainers)

github_iconTop GitHub Comments

2reactions
nareshbhatiacommented, Mar 2, 2019

@FredyC, thanks for your help on StackOverflow. I have now fully converted my GraphQL tutorial from render props to hooks (including useSubscription introduced in 0.4.1). I am sure there is room for improvement, so your feedback and suggestions would be very welcome.

I tweeted about my conversion experience here.

1reaction
nareshbhatiacommented, Mar 4, 2019

Ah, I definitely glossed over the docs on that one! Implemented your suggestion here and here. Can you please let me know if I can do any better?

It would be even nicer if useQuery() would through exceptions - that would allow me to delete all the error handling from my component and let ErrorBoundary handle it.

Read more comments on GitHub >

github_iconTop Results From Across the Web

A clean way to handle loading and error state in React ...
Let's write it in the product requirement statement. Fetch users list and show the user. Meanwhile, data is being fetched, show Loader/message.
Read more >
A generic way of handling loading-status, saving-status and ...
In this article we are going to implement a generic solution on how to fix 3 common usecases that involve redundancy in CRUD...
Read more >
How to handle loading and error states with StateNotifier ...
Loading and error states using StatefulWidget​​ Loading and error states are very common and we should handle them on every page or widget...
Read more >
Hooked with React - Error handling and loading state in react ...
We created a new state called error using useState . It was set in the catch block. try, catch is the usual way...
Read more >
Handling loading and error states the right way - Dev Genius
Easy answer: Use state objects. You should introduce state objects, to make sure that there is only a finite amount of states and...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found