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?
Related
I have this code right here
import React from "react";
import { useQuery } from "#apollo/react-hooks";
import gql from "graphql-tag";
const FETCH_POSTS_QUERY = gql`
{
getMovies {
id
title
}
}
`;
function Home() {
const { loading, data } = useQuery(FETCH_POSTS_QUERY);
if (data) {
console.log(data);
}
return (
<div>
<h1>Home</h1>
</div>
);
}
export default Home;
and when I'm running it I get lots of errors in my console. I'm not sure what Iām doing wrong.
I can tell it's caused by how useQuery is used i think. I'm not sure what's wrong though.
thanks!
I faced the same problem today, the way of useQuery that you used is correct.
This is my original code in ApolloProvider component:
import React from 'react';
import App from './App';
import { ApolloProvider } from '#apollo/react-hooks';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { createHttpLink } from 'apollo-link-http';
import ApolloClient from 'apollo-client';
const httpLink = new createHttpLink({
uri: "http://localhost:5000"
})
const client = new ApolloClient({
link: httpLink,
cache: new InMemoryCache()
})
export default(
<ApolloProvider client={ client }>
<App />
</ApolloProvider>
)
I found using apollo-client dependency would cause the errors. Then I changed it and installed #apollo/client at 3.5.10 version instead to import ApolloClient. And It finally works fine.
import React from 'react';
import App from './App';
import { ApolloProvider } from '#apollo/react-hooks';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { createHttpLink } from 'apollo-link-http';
// import ApolloClient from 'apollo-client';
import { ApolloClient } from '#apollo/client';
In addition, I've also tried to use #apollo/client at the newest version. It worked successfully as well.
I believe the issue is in the GraphQL schema, you are missing query in it. Try using the following schema:
const FETCH_POSTS_QUERY = gql`
query {
getMovies {
id
title
}
}
`;
I faced the same problem because of an old tutorial.
I configured my Apollo client in the wrong way.
Do the same as described in the get started guide from graphql and it will work perfect.
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"));
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'
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
There appears to be an error with how I'm using react-apollo. Following the docs, I am attempting to make a basic query with Apollo. This is the error I get in the browser when on the Review page. It appears that this.getClient is undefined and unable to call watchQuery.
react-apollo.browser.umd.js:417 Uncaught TypeError: this.getClient(...).watchQuery is not a function
at GraphQL.createQuery (react-apollo.browser.umd.js:417)
at GraphQL.setInitialProps (react-apollo.browser.umd.js:404)
at GraphQL.componentWillMount (react-apollo.browser.umd.js:260)
etc...
Here is the code for the Review page. I create a Review React Component, declare a graphql-tag that calls the userInfo query, and export the graphql tag connected to the Review page below.
import React from 'react'
import { graphql } from 'react-apollo';
import gql from 'graphql-tag'
class Review extends React.Component {...}
const userInfoQuery = gql`
query userInfoQuery{
userInfo {
_id
email
name {
first
last
}
isVerified
}
}`
const ReviewWithData = graphql(userInfoQuery)(Review)
export default ReviewWithData;
The issue was I was defining the wrong client in the root index.js file. So for the code below, the client I was exporting was not actually the correct Apollo client. So the variable client on the sixth import was importing some other functions. Lesson learned! Should have been more careful!
import React from 'react';
import { render } from 'react-dom';
import { BrowserRouter } from 'react-router-dom'
import { ApolloProvider } from 'react-apollo';
import App from './containers/app';
import client from './services/Apollo'
const CustomerFrontendApp = (
<ApolloProvider client={BitsyApollo.client}>
<BrowserRouter>
<App />
</BrowserRouter>
</ApolloProvider>
);
render(BitsyCustomerFrontendApp, document.getElementById('root'));