Bart
Bart

Reputation: 1609

Is there a way to let Apollo Client globally insert empty strings during loading?

I'm using Apollo Client to receive the GraphQL data for my application. Over time, I see a pattern emerging where for every value I'm querying, I have to include a conditional statement to handle the moment where my data is still loading.

Assume a query looks like this:

query TestQuery($userId: Int!) {
  getUser(id: $userId) {
    name
  }
}

Then, in every place where I want to display the user name, I have to write something like:

{ !this.props.data.loading && this.props.data.getUser.name }

or

{ this.props.data.getUser && this.props.data.getUser.name }

I don't want to display "Loading..." or a rotating spinner in any of these places. Is there a way to avoid this conditional statement by globally replacing all this.props.data.x.y.z values with null or an empty String during loading?

Thanks.

Upvotes: 0

Views: 427

Answers (1)

anhldbk
anhldbk

Reputation: 4587

How about this approach?

class GraphqlComponent extends React.Component {
    renderError(){
        // ...
    }

    renderLoading(){
        // ...
    }

    renderLoaded(){

    }

    render(){
        const { loading, error } = this.props;
        if(error){
            return renderError();
        }
        if(loading){
            return renderLoading();
        }
        return renderLoaded();
    }
}

class MyComponent extends GraphqlComponent{
    renderLoaded(){
        // your logic goes here
    }
}

Upvotes: 2

Related Questions