Skip to content
This repository has been archived by the owner on Apr 13, 2023. It is now read-only.

Network error: Network request failed #758

Closed
saadbinsaeed opened this issue Jun 6, 2017 · 6 comments
Closed

Network error: Network request failed #758

saadbinsaeed opened this issue Jun 6, 2017 · 6 comments

Comments

@saadbinsaeed
Copy link

saadbinsaeed commented Jun 6, 2017

I always got this error in my application ( react-native ) when my mobile is not connected with internet. Googled it a lot but cant resolve. It works perfect when internet is connected. Here is my networkInterface code

import ApolloClient, { createNetworkInterface } from 'apollo-client';
import { AsyncStorage } from 'react-native';
import {SubscriptionClient, addGraphQLSubscriptions} from 'subscriptions-transport-ws';

const wsClient = new SubscriptionClient('wss://172.20.32.6:5000', {
  reconnect: true,
  connectionParams: {
    accessToken: 'jka sdhkjashd jkashdjk ashdas'
  }
});

const networkInterface = createNetworkInterface({

  uri: 'http://172.20.32.6:8000/graphql',
  opts: {
    credentials: 'same-origin'
  }
});
const networkInterfaceWithSubscriptions = addGraphQLSubscriptions(
  networkInterface,
  wsClient
);
const client = new ApolloClient({
  dataIdFromObject: o => o.id,
  networkInterface: networkInterfaceWithSubscriptions

});
networkInterface.use([{
  applyMiddleware(req, next) {
    if (!req.options.headers) {
      req.options.headers = {};  // Create the header object if needed.
    }
    // get the authentication token from local storage if it exists
    AsyncStorage.getItem('sessionToken').then((token) => {
      req.options.headers.Authorization = token ? `${token}` : null;
      next();
    }
    );
  }
}]);
export default client;

As i already said it works perfect when my app is connected with internet. But my application crashes when its not. How can i handle this error?
ExceptionsManager.js:71 Unhandled (in react-apollo) Error: Network error: Network request failed

Version

  • apollo-client@<1.0.4>
  • react-apollo@<1.1.1>
@ghost
Copy link

ghost commented Jun 7, 2017

Same problem here, I have no idea how to handle errors when the user is offline.
This is already discussed here : #604

@saadbinsaeed
Copy link
Author

saadbinsaeed commented Jun 8, 2017

There was a mistake in my application logic. I was executing the query on the index (Login) page. Which leads to the network failure and application crashes. The exception was not handled so i handled it now by checking that

if(this.props.data.error)
  return <ErrorComponent /> ;

@TheoMer
Copy link

TheoMer commented Jun 8, 2017

@saadbinsaeed Can you repost your Apollo client code inclusive of your exception handling, so as to ascertain where it's being handled. Are you handling it within 'networkInterface.use' or catching it after your mutation?

@saadbinsaeed
Copy link
Author

saadbinsaeed commented Jun 13, 2017

Hi @TheoMer Sorry for replying late, I am not handling it within the networkInterface.use, i just catched the exception after the query execution. I am not posting the code because it do not follows the Actual Apollo's standards although it is working :P But I will try to explain that what causes trouble to me. May be you are also following the same approach. Let me explain you the scenario.

LoginContainer ( index ) page was wrapped in a query and a mutation
export default Login = graphql(Viewer)(graphql(mutation)(LoginContainer));

This is my query and mutation

const mutation = gql`mutation LoginMutation ($credentials:JSON){
  Account{
    AccountLogin (input:{credentials: $credentials}){
      obj
    }
  }
}`;
const Viewer = gql` query Viewer{
    viewer {
        me{
            username
            email
            id
            firstName
            lastName
        }
    }
}`;
  • Mutation: to handle the authorization and for setting accessToken of the LoggedIn user required by loop-back
  • Query ( The problem ): To refetch the user data ( worst approach )

According to the apollo-documentation when you wrap a component in graphql query, it automatically calls. So in my opinion you have to manually handle the exception in each component which is wrapped in a query.

When i start the app on offline mode, Login container renders, try to execute the query, app crashes. This query should have been executed in componentDidMount() of the LoginContainer so that user may able to see at least the login screen in case of offline mode or the developer should have used the refetchQueries option after the execution of its mutation.

Each component which is wrapped in a query should handle the exception although this is horribly repetitious,

if(this.props.data.error)
  return <ErrorComponent /> ; // or set the dummy state of your component 

I hope that i didn't confuse you much.

@TheoMer
Copy link

TheoMer commented Jun 13, 2017

Hi @saadbinsaeed Many thanks for your reply. My issue was I presumed cachePolicy and fetchPolicy were going to resolve the issue, but alas not:

** imports **

// Root Query
const allPostsCommentsQuery = graphql(All_Posts_Comments_Query, {
  options: {
    cachePolicy: 'offline-critical', 
    fetchPolicy: 'cache-first',
  },
});

function mapStateToProps(state) {
   return {
    auth: state.auth
  };
}

export const mapDispatchToProps = (dispatch) => {
  return bindActionCreators(actionCreators, dispatch);
}

export default withRouter(compose(
  allPostsCommentsQuery,
  connect(mapStateToProps, mapDispatchToProps)
)(Main));

I will make the appropriate amendments as you explained.

@saadbinsaeed
Copy link
Author

saadbinsaeed commented Jun 13, 2017

My Pleasure @TheoMer, I was first assuming that this is due to the networkInterfaceWithSubscriptions because it contains the socket connection but it wasn't. For more understanding have a look at Sabativi's repo. He has nicely explained that how we can handle this error.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants