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.

Query data and error are undefined

See original GitHub issue

Intended outcome: I’m using useQuery to query and render some data. The loading prop works as expected, the value is true and then changes to false. When loading is false, data and error are both undefined.

I checked the network tab and the data is being received (I see the data prop)

Screen Shot 2021-04-27 at 1 41 51 PM

I also checked what’s going on with the Apollo chrome extension and I can see the data

Screen Shot 2021-04-27 at 1 34 24 PM Screen Shot 2021-04-27 at 1 34 10 PM

I also was able to verify the correct result from the BE using the fetch API

Screen Shot 2021-04-27 at 1 34 47 PM

Actual outcome: data and error props from useQuery are undefined.

How to reproduce the issue:

Here’s the component that uses useQuery and fetch

const QUERY = gql`
  query AccountStatus {
    accountStatus {
      __typename
      missingCode
      completed
      reason
    }
  }
`

const MissingThings = () => {
  const x = useQuery(QUERY)

  const { loading, data, error } = x

  console.log('--x', x)

  useEffect(() => {
    fetch(`${process.env.REACT_APP_GRAPHQL_URL}`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization:
          'Bearer <TOKEN>',
      },
      body: JSON.stringify({
        variables: {},
        query: `
        query AccountStatus {
          accountStatus {
            __typename
            missingCode
            completed
            reason
          }
        }
        
        `,
      }),
    })
      .then((result) => result.json())
      .then((result) => console.log('--result', result))
      .catch(console.error)
  }, [])

  if (loading) {
    return null
  }

  if (error) {
    console.log('--error', error)
    return null
  }

  console.log('--data', data)

  return <div>All good</div>
}

And this is the Apollo Client

const ApolloClientProvider = ({ children }: any) => {
  const { auth, account } = useGlobalProvider()
  const headers =
    auth && account ? { Authorization: `Bearer ${auth?.token}` } : {}

  console.log('--headers', headers)
  console.log('--auth', auth)

  const wsLink = new WebSocketLink({
    uri: process.env.REACT_APP_GRAPHQL_WS_URL as string,
    options: {
      reconnect: true,
      connectionParams: () => ({
        headers,
      }),
    },
  })

  const httpLink = new HttpLink({ uri: process.env.REACT_APP_GRAPHQL_URL })

  const authMiddleware = new ApolloLink((operation, forward) => {
    // add the authorization to the headers
    operation.setContext({
      headers:
        auth && account ? { Authorization: `Bearer ${auth?.token}` } : {},
    })

    return forward(operation)
  })

  const splitLink = split(
    ({ query }) => {
      const definition = getMainDefinition(query)
      return (
        definition.kind === 'OperationDefinition' &&
        definition.operation === 'subscription'
      )
    },
    wsLink,
    httpLink,
  )

  const logoutLink = onError((error) => {
    console.log('APOLLO ERROR!', error)

    if (
      error.networkError?.message.includes('JWTExpired') ||
      error.graphQLErrors?.some(
        ({ extensions, message }) =>
          extensions?.code === 'invalid-jwt' || message.includes('JWTExpired'),
      )
    ) {
      navigate('/logout')
    }
  })

  const client = new ApolloClient({
    cache: new InMemoryCache(),
    link: ApolloLink.from([logoutLink, authMiddleware, splitLink]),
  })

  return <ApolloProvider client={client}>{children}</ApolloProvider>
}

Versions System: OS: macOS 11.2.3 Binaries: Node: 14.8.0 - ~/n/bin/node npm: 6.14.7 - ~/n/bin/npm Browsers: Chrome: 90.0.4430.72 Safari: 14.0.3 npmPackages: @apollo/client: ^3.3.15 => 3.3.15

Issue Analytics

  • State:open
  • Created 2 years ago
  • Reactions:27
  • Comments:41 (6 by maintainers)

github_iconTop GitHub Comments

5reactions
eranimocommented, Jun 8, 2022

Why is this closed?

5reactions
hwillsoncommented, Jan 4, 2022

This should be resolved in @apollo/client@latest - let us know if not.

Read more comments on GitHub >

github_iconTop Results From Across the Web

React Query return undefined data while in network tab the ...
javascript - React Query return undefined data while in network tab the data exists but it does not show on the page -...
Read more >
Handling `undefined` in React Query and Typescript - neldeles
For placeholderData , query will be in error state and data will be undefined . Regardless though, one constant remains. The typescript types ......
Read more >
Getting Error field for Query component as undefined when I ...
Hi, I'm trying to test my API and error handling using a higher order component in next js. I have used a query...
Read more >
useQuery | TanStack Query Docs
Must return a promise that will either resolve data or throw an error. The data cannot be undefined . enabled: boolean. Set this...
Read more >
Null and undefined (Reference)
In this instance, the value of the email property is undefined . When this query is run no data is returned. This is...
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