Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot read property '0' of undefined #4207

Closed
anarerdene opened this issue Oct 18, 2019 · 5 comments
Closed

Cannot read property '0' of undefined #4207

anarerdene opened this issue Oct 18, 2019 · 5 comments
Labels
AppSync Related to AppSync issues bug Something isn't working question General question

Comments

@anarerdene
Copy link

anarerdene commented Oct 18, 2019

Describe the bug
A clear and concise description of what the bug is.

Im using AWS Amplify

"aws-amplify": "1.2.2",
"aws-amplify-react": "^2.5.2",
"react-apollo": "^3.1.3"

To Reproduce

I'M trying to connect Apollo hooks to aws Enpoint but throwing this error "Cannot read property '0' of undefined"

My query is :

image

and this is main code:

import React, {Component} from 'react';
import {withApollo} from '../../lib/apollo';
import gql from 'graphql-tag';
import {useQuery} from '@apollo/react-hooks';
import {listUsers} from '../../src/graphql/queries';


const Category = () => {
  const {loading, error, data} = useQuery(gql(listUsers.ListUsers));

  if (loading) return 'Loading...';
  if (error) return `Error! ${error.message}`;

  return <Main>ewfewf</Main>;
};

export default withApollo(Category);
```javascript
@anarerdene anarerdene added the bug Something isn't working label Oct 18, 2019
@elorzafe
Copy link
Contributor

@anarerdene if you want to use Apollo with AppSync you will need to use either AppSyncSDK or Auth/Subscriptions links. More info here

@elorzafe elorzafe added AppSync Related to AppSync issues question General question labels Oct 18, 2019
@anarerdene
Copy link
Author

Hi @elorzafe, thanks for advice. I'm using AppSyncSDK and result is

"TypeError: this.currentObservable.query.getCurrentResult is not a function"

here is my apollo config.

import React, {useMemo} from 'react';
import Head from 'next/head';
import {ApolloProvider} from 'react-apollo';
import {ApolloClient, InMemoryCache, HttpLink} from 'apollo-boost';
import {createHttpLink} from 'apollo-link-http';
import fetch from 'isomorphic-unfetch';

// aws (Amu Custom)
import Amplify, {Auth} from 'aws-amplify';
import AWSAppSyncClient from 'aws-appsync';
import config from '../src/aws-exports';

Amplify.configure({
  ...config,
  cookieStorage: {
    // REQUIRED - Cookie domain (only required if cookieStorage is provided)
    domain: '127.0.0.1',
    // OPTIONAL - Cookie path
    path: '/',
    // OPTIONAL - Cookie expiration in days
    expires: 365,
    // OPTIONAL - Cookie secure flag
    // Either true or false, indicating if the cookie transmission requires a secure protocol (https).
    secure: false
  }
});

let apolloClient = null;

/**
 * Creates and provides the apolloContext
 * to a next.js PageTree. Use it by wrapping
 * your PageComponent via HOC pattern.
 * @param {Function|Class} PageComponent
 * @param {Object} [config]
 * @param {Boolean} [config.ssr=true]
 */
export function withApollo(PageComponent, {ssr = true} = {}) {
  const WithApollo = ({apolloClient, apolloState, ...pageProps}) => {
    const client = useMemo(() => apolloClient || initApolloClient(apolloState), []);
    return (
      <ApolloProvider client={client}>
        <PageComponent {...pageProps} />
      </ApolloProvider>
    );
  };

  // Set the correct displayName in development
  if (process.env.NODE_ENV !== 'production') {
    const displayName = PageComponent.displayName || PageComponent.name || 'Component';

    if (displayName === 'App') {
      console.warn('This withApollo HOC only works with PageComponents.');
    }

    WithApollo.displayName = `withApollo(${displayName})`;
  }

  // Allow Next.js to remove getInitialProps from the browser build
  if (ssr || PageComponent.getInitialProps) {
    WithApollo.getInitialProps = async ctx => {
      const {AppTree} = ctx;

      // Initialize ApolloClient, add it to the ctx object so
      // we can use it in `PageComponent.getInitialProp`.
      const apolloClient = (ctx.apolloClient = initApolloClient());

      // Run wrapped getInitialProps methods
      let pageProps = {};
      if (PageComponent.getInitialProps) {
        pageProps = await PageComponent.getInitialProps(ctx);
      }

      // Only on the server:
      if (typeof window === 'undefined') {
        // When redirecting, the response is finished.
        // No point in continuing to render
        if (ctx.res && ctx.res.finished) {
          return pageProps;
        }

        // Only if ssr is enabled
        if (ssr) {
          try {
            // Run all GraphQL queries
            const {getDataFromTree} = await import('@apollo/react-ssr');
            await getDataFromTree(
              <AppTree
                pageProps={{
                  ...pageProps,
                  apolloClient
                }}
              />
            );
          } catch (error) {
            // Prevent Apollo Client GraphQL errors from crashing SSR.
            // Handle them in components via the data.error prop:
            // https://www.apollographql.com/docs/react/api/react-apollo.html#graphql-query-data-error
            console.error('Error while running `getDataFromTree`', error);
          }

          // getDataFromTree does not call componentWillUnmount
          // head side effect therefore need to be cleared manually
          Head.rewind();
        }
      }

      // Extract query data from the Apollo store
      const apolloState = apolloClient.cache.extract();

      return {
        ...pageProps,
        apolloState
      };
    };
  }

  return WithApollo;
}

/**
 * Always creates a new apollo client on the server
 * Creates or reuses apollo client in the browser.
 * @param  {Object} initialState
 */
function initApolloClient(initialState) {
  // Make sure to create a new client for every server-side request so that data
  // isn't shared between connections (which would be bad)
  if (typeof window === 'undefined') {
    return createApolloClient(initialState);
  }

  // Reuse client on the client-side
  if (!apolloClient) {
    apolloClient = createApolloClient(initialState);
  }

  return apolloClient;
}

/**
 * Appsync With Apollo (Amu Custom)
 */

function createApolloClient(initialState) {
  const client = new AWSAppSyncClient(
    {
      url: config.aws_appsync_graphqlEndpoint,
      region: config.aws_appsync_region,
      auth: {
        type: config.aws_appsync_authenticationType,
        jwtToken: async () => (await Auth.currentSession()).getIdToken().getJwtToken()
      },
      disableOffline: true
    },
    {
      cache: new InMemoryCache().restore(initialState || {}),
      ssrMode: true
    }
  );

  return client;
}

@Amplifiyer
Copy link
Contributor

@anarerdene, it looks like the issue is with the apollo-client package used in appsync. Can you try some suggestions mentioned here apollographql/react-apollo#3148 towards the end that work with appsync client?

@stale
Copy link

stale bot commented Oct 27, 2019

This issue has been automatically closed because of inactivity. Please open a new issue if are still encountering problems.

@github-actions
Copy link

This issue has been automatically locked since there hasn't been any recent activity after it was closed. Please open a new issue for related bugs.

Looking for a help forum? We recommend joining the Amplify Community Discord server *-help channels or Discussions for those types of questions.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Jun 12, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
AppSync Related to AppSync issues bug Something isn't working question General question
Projects
None yet
Development

No branches or pull requests

4 participants