Cannot connect apollo client to aws appsync - reactjs

I have a web app using aws appsync as backend and react + apollo client (v3) as front end. But when I try connecting apollo client to appsync, I get an error message from the library:
./node_modules/aws-appsync-react/lib/offline-helpers.js
Module not found: Can't resolve 'react-apollo' in '/Users/mypath/web/node_modules/aws-appsync-react/lib'
Here's the config for the client:
import AWSAppSyncClient from "aws-appsync";
import AppSyncConfig from "./aws-exports";
export const apolloClient = new AWSAppSyncClient({
url: AppSyncConfig.aws_appsync_graphqlEndpoint,
region: AppSyncConfig.aws_appsync_region,
auth: {
type: AppSyncConfig.aws_appsync_authenticationType,
apiKey: AppSyncConfig.aws_appsync_apiKey,
},
});
And the in my App.ts:
import { ApolloProvider } from "#apollo/client";
import { Rehydrated } from "aws-appsync-react";
import { apolloClient } from "./apollo";
...
<ApolloProvider client={apolloClient}>
<Rehydrated>
<MyApp />
</Rehydrated>
</ApolloProvider>
Looks like a compatibility issue?
I'm using "#apollo/client": "^3.1.3", "aws-appsync": "^4.0.0","aws-appsync-react": "^4.0.0",.

It is a compatibility issue. Current version of aws-appsync doesn't support apollo-client v3, see this thread for progress:
https://github.com/awslabs/aws-mobile-appsync-sdk-js/issues/448
Best workaround is this: Proper way to setup AWSAppSyncClient, Apollo & React
Note the workaround does use two deprecated libraries but can be slightly improved as:
import { ApolloClient, ApolloLink, InMemoryCache } from "#apollo/client";
import { createAuthLink } from "aws-appsync-auth-link";
import { createHttpLink } from "apollo-link-http";
import AppSyncConfig from "./aws-exports";
const url = AppSyncConfig.aws_appsync_graphqlEndpoint;
const region = AppSyncConfig.aws_project_region;
const auth = {
type: AppSyncConfig.aws_appsync_authenticationType,
apiKey: AppSyncConfig.aws_appsync_apiKey,
};
const link = ApolloLink.from([
// #ts-ignore
createAuthLink({ url, region, auth }),
// #ts-ignore
createHttpLink({ uri: url }),
]);
const client = new ApolloClient({
link,
cache: new InMemoryCache(),
});
export default client;

Related

Can Apollo graphql be used with Nextjs without having to install react-router-dom?

An ApolloProvider wraps an app:
<ApolloProvider client={client}>
<App />
</ApolloProvider>
The problem is, in nextjs you can declare route components in the pages folder WITHOUT having to add them to App.js
Which leads to the error "Invariant Violation: Could not find "client" in the context or passed in as an option. "
Can Apollo be used in these components with the native Nextjs way of handling routes?
This is what I did with mine, make a separate folder I called it apollo folder just like this:
then inside that folder create a file name it whatever you want then put this code or whatever code for you apollo client
apollo/ apolloClient.js
import ApolloClient from "apollo-client";
import { InMemoryCache } from "apollo-cache-inmemory";
import { createHttpLink } from "apollo-link-http";
import { ApolloProvider } from "#apollo/react-hooks";
import { setContext } from "apollo-link-context";
const httpLink = createHttpLink({
uri: "http://localhost:5000",
});
const authLink = setContext(() => {
const token = localStorage.getItem("jwtToken");
return {
headers: {
Authorization: token ? `Bearer ${token}` : "",
},
};
});
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache(),
});
export default client;
You have to export the client or what I did with mine and go to the _app.js:
import "../styles/globals.css";
import { ApolloProvider } from "#apollo/react-hooks";
import client from "../apollo/apolloClient";
function MyApp({ Component, pageProps }) {
return (
<ApolloProvider client={client}>
<Component {...pageProps} />
</ApolloProvider>
);
}
export default MyApp;
We have imported the client from the apolloClient.js file that we just created and exported the client
Hope this is what you mean.

How can one deploy Apollo Server with Create-React-App?

I'm trying to deploy my application to a production environment, but having some trouble wiring it all together.
I've got a create-react-app for my frontend, which is served up by a simple express/serve server. On the backend, I've got NGINX proxying successfully to my API server, which is using Apollo to serve my data. The API is running on port 4000.
The Apollo-Server is as-follows, and works fine:
import { resolve } from "path";
import dotenv from "dotenv";
const envi = process.env.NODE_ENV;
dotenv.config({ path: resolve(__dirname, `../.${envi}.env`) });
import "reflect-metadata";
import { connect } from "./mongodb/connect";
import { buildSchema } from "type-graphql";
import { ApolloServer } from "apollo-server";
import { SenateCommitteeResolver, HouseCommitteeResolver } from "./resolvers";
import { populateDatabase } from "./util";
(async () => {
// Connect to MongoDB
await connect();
console.log(`📊 Databases connected`);
const schema = await buildSchema({
resolvers: [HouseCommitteeResolver, SenateCommitteeResolver],
emitSchemaFile: resolve(__dirname, "schema.gql"),
});
// If development, set database docs
envi === "development" && (await populateDatabase());
// Launch the server!
const server = new ApolloServer({
schema,
playground: true,
});
// Server listens at URL
const { url } = await server.listen(4000);
console.log(`🚀 Server ready, at ${url}`);
})();
I'm trying to connect my express server to the Apollo Server, but that's where I'm running into problems. The application is supposed to connect using Apollo's Client and HTTP Link, because I'm using Apollo Client on the frontend too:
import React, { useEffect } from "react";
import { AppRouter } from "./routers";
import ReactGA from "react-ga";
import { ApolloProvider } from "#apollo/client";
import client from "./graphql/client";
import "./styles/index.scss";
function App(): React.ReactElement {
return (
<ApolloProvider client={client}>
<AppRouter />
</ApolloProvider>
);
}
export default App;
And here's the client file:
import { ApolloClient, InMemoryCache, createHttpLink } from "#apollo/client";
const httpLink = createHttpLink({ uri: process.env.REACT_APP_API as string });
const cache = new InMemoryCache();
const client = new ApolloClient({
link: httpLink,
cache,
connectToDevTools: true,
});
export default client;
However, when the user navigates to the site and the site itself tries to make a request to my backend, I'm getting a CORS error:
Access to fetch at 'https://www.cloture.app/' from origin 'https://cloture.app' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
What's going wrong? How can I connect Apollo's client with my Apollo Server on the backend?
Adding it here, because the suggestion requires some code.
Try adding :
const server = new ApolloServer({
schema,
playground: true,
cors: {
origin: "*" // it will allow any client to access the server, but you can add specific url also
}
});

Could not find "client" in the context or props of Mutation

After executing my React Native app I've ran into this error:
Could not find "client" in the context or props of Mutation. Wrap the root component in an <ApolloProvider>, or pass an ApolloClient instance via props.
Here's my apollo client
import { Platform } from "react-native";
import { ApolloClient, InMemoryCache } from "#apollo/client";
// To access our host machine and not the device itself we use a special ip on android
// If we are using IOS access localhost:4000 else use 10.0.0.2:4000
const host =
Platform.OS === "ios" ? "http://localhost:4000" : "http://10.0.2.2:4000";
export const client = new ApolloClient({
uri: host,
cache: new InMemoryCache(),
});
And here's index.tsx which wraps my root component:
import { ApolloProvider } from '#apollo/client';
import { client } from "./apollo";
import { Routes } from "./routes/index";
export default class App extends React.PureComponent {
render() {
return (
<ApolloProvider client={client}>
<Routes />
</ApolloProvider>
);
}
}
Before V 3.0 react-apollo and apollo-client (And other sub-packages) were on separate packages (Made a lot of issues/errors related to packages versions. Issue 2042 -or- issue 2900).
The best idea is to Migrating to Apollo Client 3.0.
The react-apollo package has been deprecated, and the functionality
offered by each of the above packages can now be accessed from
#apollo/client. Migrating to Apollo Client 3.0
Apollo V3.0 Great "get-started"/tuturial example + sandbox:
https://www.apollographql.com/docs/react/get-started/
client
In your case looks like the client is undefined. Run and test:
console.log(client); /* return object -or- not? */
Try to run this code in one file (If this code works fine - separate the files you want and use module.exports).
import React from "react";
import { render } from "react-dom";
import {
ApolloClient,
InMemoryCache,
ApolloProvider,
useQuery,
gql
} from "#apollo/client";
export const client = new ApolloClient({
uri: "https://48p1r2roz4.sse.codesandbox.io",
cache: new InMemoryCache()
});
export default class App extends React.PureComponent {
render() {
return (
<ApolloProvider client={client}>
<h2>My first Apollo app <span>🚀</span></h2>
</ApolloProvider>
);
}
}
render(<App/>, document.getElementById("root"));

How can I get my http and subscription to work on client with graphQL?

I finally finished my backend with apollo.
Now I moved to the frontend.
I made it work with the normal http connection and fetched some messages from the server (chat app).
Now I also tried to connect the subscription link to it (which was very confusing in itself because there are a few examples outside and everybody does it a bit differently, but neither worked).
So here is how my index file looks on react frontend:
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import * as serviceWorker from "./serviceWorker";
import { ApolloClient } from "apollo-client";
import { ApolloProvider } from "react-apollo";
import { WebSocketLink } from "apollo-link-ws";
import { ApolloLink } from "apollo-link";
import { HttpLink } from "apollo-link-http";
import { InMemoryCache } from "apollo-cache-inmemory";
const wsLink = new WebSocketLink({
uri: `ws://localhost:4000/graphql`,
options: {
reconnect: true
}
});
// Create an http link:
const httpLink = new HttpLink({
uri: "http://localhost:4000/graphql"
});
const link = ApolloLink.from([httpLink, wsLink]);
const client = new ApolloClient({
link,
cache: new InMemoryCache()
});
ReactDOM.render(
<ApolloProvider client={client}>
<App />
</ApolloProvider>,
document.getElementById("root")
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
serviceWorker.unregister();
I also tried different methods for example with split from apollo-link like this:
const link = split(
// split based on operation type
({ query }) => {
const definition = getMainDefinition(query);
return (
definition.kind === "OperationDefinition" &&
definition.operation === "subscription"
);
},
wsLink,
httpLink
);
I also tried it with ApolloClient from apollo-boost instead of apollo-client.
Can somebody please help me out, because I can't get it to work.
Error message is always:
WebSocket connection to 'ws://localhost:4000/graphql' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
If you want to see the full code: https://github.com/SelfDevTV/graphql-simple-chat

Cant connect React to Graphcool backend

Im trying to get a basic React + Graphcool project setup.
Ive initialised the Graphcool backend so I can see the playground at: https://api.graph.cool/simple/v1/MY-KEY
I can run this query in the playground and see results:
query {
allGroups {
id
description
}
}
However I cant connect this to the React front-end. This is my index.js:
import React from 'react';
import ReactDOM from 'react-dom';
// GraphQL
import { ApolloProvider } from 'react-apollo';
import { ApolloClient } from 'apollo-client';
import { HttpLink } from 'apollo-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';
// Components
import App from './components/App/App';
const httpLink = new HttpLink({
uri: 'https://api.graph.cool/simple/v1/MY-KEY',
});
const client = new ApolloClient({
link: httpLink,
cache: new InMemoryCache(),
});
ReactDOM.render(
<ApolloProvider client={client}>
<App />
</ApolloProvider>,
document.getElementById('App'),
);
In App.js:
import React from 'react';
import gql from 'graphql-tag';
import graphql from 'react-apollo';
const myQuery = gql`
query {
allGroups {
id
description
}
}
`;
const App = () => {
return (
<div>
<h1>Application</h1>
<h2>Groups:</h2>
</div>
);
};
// export default App;
export default graphql(myQuery)(App);
But I get an error:
Uncaught TypeError: (0 , _reactApollo2.default) is not a function
I don't know if this relevant or not but my IDE gives me the following error on the 'allGroups' line in App.js:
cannot query field "allGroups" on type "Query"
thats graphql import error, lets try this
In App.js:
import { graphql, } from 'react-apollo';
you'd better using a graphcool play ground to test you query and mutation
. then connect to React.Otherwise, there are many detail to debug.
here is my procedure
graphcool deploy is ok?
go to playground schema is ok?
query and mutation is ok?
configure apollo client and connect to React component. is ok?
In the component console.log(this.props.data) is ok ?
This is my flow.
And the most thing when you add some schema and resolvser, you must be add then to graphcool.yaml files. otherwise, graphcool can't find you schema and query method.
Is this your address?
here is mine
can you see difference?

Resources