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

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"));

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.

Cannot connect apollo client to aws appsync

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;

React Apollo Error: Invariant Violation: Could not find "client" in the context or passed in as an option

I'm building a project using React, Apollo and Next.js. I'm trying to update react-apollo to 3.1.3 and I'm now getting the following error when viewing the site.
Invariant Violation: Could not find "client" in the context or passed in as an option. Wrap the root component in an , or pass an ApolloClient instance in via options.
If I downgrade the react-apollo package to 2.5.8 it works without issue so I'm thinking something has changed between 2.5 and 3.x but can't find anything in the react-apollo or next-with-apollo documentation to indicate what that might be. Any assistance would be greatly appreciated.
withData.js
import withApollo from 'next-with-apollo';
import ApolloClient from 'apollo-boost';
import { endpoint } from '../config';
function createClient({ headers }) {
return new ApolloClient({
uri: endpoint,
request: operation => {
operation.setContext({
fetchOptions: {
credentials: 'include'
},
headers
});
},
// local data
clientState: {
resolvers: {
Mutation: {}
},
defaults: {}
}
});
}
export default withApollo(createClient);
_app.js
import App from 'next/app';
import { ApolloProvider } from 'react-apollo';
import Page from '../components/Page';
import { Overlay } from '../components/styles/Overlay';
import withData from '../lib/withData';
class MyApp extends App {
static async getInitialProps({ Component, ctx }) {
let pageProps = {};
if (Component.getInitialProps) {
pageProps = await Component.getInitialProps(ctx);
}
// this exposes the query to the user
pageProps.query = ctx.query;
return { pageProps };
}
render() {
const { Component, apollo, pageProps } = this.props;
return (
<ApolloProvider client={apollo}>
<Overlay id="page-overlay" />
<Page>
<Component {...pageProps} />
</Page>
</ApolloProvider>
);
}
}
export default withData(MyApp);
In my case, I found that I had react-apollo#3.0.1 installed as well as #apollo/react-hooks#3.0.0. Removing #apollo/react-hooks and just relying on react-apollo fixed the invariant issue for me. Make sure that you aren't using any mismatched versions in your lock file or package.json
This is what someone said in a GitHub issue thread, which, was the case for me too. Make sure you try it!
I've had a mixture of solutions, i think it does boil down to how you initially go about setting up all the related packages.
"Some packages don't work well with others when it comes to connecting the client to Reacts Context.Provider"
I've had two go two fixes that seem to work well (With new projects and updating old):
1: Uninstall #apollo/react-hooks
Then:
import { ApolloProvider } from "#apollo/client";
instead of:
import { ApolloProvider } from "react-apollo";
(This allowed me to keep the "#apollo/react-hooks" package without conflicts)
3: Double-check that the server that is serving HttpLink client URI is up and running for the client to connect (This give a different error then the one were talking about but is still good to know in this situation)
Conclusion: It can be a slight bit of trial and error, but try to use the matching/pairing packages
I uninstalled 'react-apollo', used '#apollo/client' instead, it solved the issue for me.
import gql from 'graphql-tag';
import {graphql} from '#apollo/react-hoc';
import { ApolloClient, InMemoryCache } from '#apollo/client';
import { ApolloProvider } from '#apollo/react-hooks';
These imports worked for me perfectly. I had a great time debugging and finding different import libraries but finally after 3 hours this was the solution for using graphql and appolo.
I found this to be the solution as well, though now I'm only using #apollo/client and apollo-link since they are the latest version.
import {ApolloProvider} from 'apollo/client' instead 'react-apollo'or '#apollo/react-hooks'

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