Fatah
Fatah

Reputation: 2286

Unhandled Network Error 401 When using Apollo in react native & empty graphql response

I am building a react-native app using create-react-native-app cli Here are the packages I am using. All of the latest stable except fiber "dependencies": { "apollo-cache-inmemory": "^1.0.0", "apollo-client": "^2.0.1", "apollo-link": "^1.0.0", "apollo-link-error": "^1.0.0", "apollo-link-http": "^1.0.0", "expo": "^21.0.0", "graphql": "^0.11.7", "graphql-tag": "^2.5.0", "react": "16.0.0-alpha.12", "react-apollo": "^2.0.0", "react-native": "^0.48.4", "react-navigation": "^1.0.0-beta.15" }

The app runs and routing navigation works fine. I have two routes, App and FeedList.

the app talks to github graph api( I dont know if github access token is required, if so, i haved added it but I don't know if that's the correct way)

Feedlist is wrapped in a graphql HoC component and its props has a data which is already populated with results of the graphql request(even if the request fails)

You can refer to The structure of the data prop


App Component

import React, { Component } from 'react'
import ApolloClient from 'apollo-client'
import { ApolloLink } from 'apollo-link'
import { createHttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'
import { ApolloProvider } from 'react-apollo';
import { onError } from 'apollo-link-error';
import Router from './router'

class App extends Component {
  createClient() {
    const httpLink = createHttpLink({ uri: 'https://api.github.com/graphql'})

    // handle network error
    const errorLink = onError(({ networkError }) => {
        if (networkError.statusCode === 401) {
          console.log(networkError)
        }
      // let errorMessage = networkError.statusCode === 401 ? 'Network error 104, handled' : 'link sucess'
      // console.log(errorMessage, networkError)
    })

    // apply widdleware to add access token to request
    let middlewareLink =  new ApolloLink((operation, forward) => {
      operation.setContext({
        headers: {
          authorization: 'GITHUB_ACCESS_TOKEN'
        }
      })
      return forward(operation)
    })
    const link = middlewareLink.concat(httpLink)
    

    // Initialize Apollo Client with URL to our server
    return new ApolloClient({
    link: link,
    cache: new InMemoryCache(),
    })
  }
  render () {
    return (
      <ApolloProvider client={this.createClient()}>
        <Router />
      </ApolloProvider>
    )
  }
}

export default App


FeedList Component

import React, { Component } from 'react';
import { Text } from 'react-native';
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';

// The data prop, which is provided by the wrapper below contains,
// a `loading` key while the query is in flight and posts when ready
const FeedList = ({ data }) => {
  console.log(data) // returns default from HoC injected props
  console.log('FeedList Eroor!!',data.error) // returns undefined
  return data.error ? <Text> Error Fetching posts</Text>:<Text>fetching posts... </Text>
}

// The `graphql` wrapper executes a GraphQL query and makes the results
// available on the `data` prop of the wrapped component (PostList here)
export default graphql(gql`{
  search(type: REPOSITORY, query: "react", first: 20) {
    edges {
      node {
        ... on Repository {
          nameWithOwner
          owner {
            login
          }
        }
      }
    }
  }
}`, { options: { notifyOnNetworkStatusChange: true } })(FetchPost);

The important parts are the the Wrapped FeedList component which does log the data from props and the createClient() method inside App component. I followed this to try and catch the error that may happen during the data request.

The HoC wrapper component does its job and FeedList's data prop has has everything but the response from the api.

browser debug

Note that the error does not crash app

expo android debugger

The above image shows also the same error message as on the expo simulator on android

So I guess the question i have is

  1. How do I catch the error? Here is a similar issue
  2. If its the way I structured my query thats the problem. How do I correctly get the github api to return data correctl?

Here is the repo you can run and reproduce the error

Note that Issue#1 in that repo is similar to this SO question and I have already fixed it by handling data.error as per the documentation

Also note that most of the documentation is for the older versions of apollo-client > v2.x.x

Issue #2 is exactly what I am asking here. Thank you for your help

Upvotes: 0

Views: 5029

Answers (1)

Daniel Rearden
Daniel Rearden

Reputation: 84897

A 401 status means invalid authentication. As you've guessed, you need a valid OAuth token to send with your request. For development purposes, you can just generate one. Make sure you include the scopes outlines as outlined here:

user
public_repo
repo
repo_deployment
repo:status
read:repo_hook
read:org
read:public_key
read:gpg_key

You don't want users accessing the API through your credentials, so eventually you'll need to implement an OAuth2 authentication flow in your app to generate a token for each end user.

Upvotes: 2

Related Questions