Hello,
Using expo/react-native, I get this error when I try make a graphql-query from a modal. I.E the component only gets mounted when you click on a link [the modal slides in]. The graphql-query seems to work in any other component.
my root component is wrapped in a ApolloProvider
<ApolloProvider client={client}>
<View style={styles.container}>
<Navigator navigatorViews={navigatorViews} routeConfig={routeConfig} />
</View>
</ApolloProvider>
I'm not quoting my query code as it works fine outside the modal, is there some gotchas for components that are mounted dynamically ?
Intended outcome: Execute graphql query from a component that is mounted dynamically
Actual outcome: see error above
How to reproduce the issue: Make graphql query from a component that is mounted in dynamically
Version
Hi @farzd,
Have you solved this issue? I have the same thing right now.
I just encountered the same issue, anyone solved this?
@thierryskoda @oakmad
Sorry guys, i've not revisited this yet. But a work around would be to either import the client again
https://stackoverflow.com/questions/40634872/do-i-need-to-bind-to-a-component-to-use-the-apollo-react-client-even-if-it-has-n
or use HOC from apollo
http://dev.apollodata.com/react/higher-order-components.html#withApollo
OK Thanks @farzd Honestly it's far from ideal in terms of solution, decorators cause me grief in other ways. I was under the impression that is I wrapped my app then client was available all the way down. I'll keep looking and post if I find anything, thanks again.
@oakmad client should be available all the way through, can you post your code?
I was having an issue because i'm cloning my component etc [i'm assuming]
Yeah sure. I've trimmed some non pertinent code, I'm sure its a silly mistake. When I include the phone component in the form, I see the error "Warning: Failed context type: The context client
is marked as required in Apollo(Phone)
, but its value is undefined
."
Parent Component:
import React, { Component } from 'react';
import { graphql, compose } from 'react-apollo';
import gql from 'graphql-tag';
import Phone from './phone';
const PersonSave = gql\`
mutation PersonSave($id: String,
$firstName: String!,
$lastName: String!,
$phone: String!
$slug: String!) {
PersonSave(id: $id,
firstName: $firstName,
lastName: $lastName,
phone: $phone,
slug: $slug) {
id
slug
firstName
lastName
phone
}
}`;
const Organizations = gql`query Organizations {
organizations {
id
name
}
}`;
class PersonForm extends Component {
constructor(props) {
super(props);
this.state = this.props.person;
console.log(this.state);
this.handleChange = this.handleChange.bind(this);
this.checkEmail = this.checkEmail.bind(this);
}
checkEmail(event) {
const value = event.target.value;
const emailRegex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
let emailError;
if (!emailRegex.test(value)) {
emailError = 'Invalid email address';
}
this.setState({
email: value,
emailError,
});
}
handleChange(event) {
const target = event.target;
const name = target.name;
const value = target.type === 'checkbox' ? target.checked : target.value;
this.setState({
[name]: value,
});
}
render() {
return (
<Form>
<Phone
phone={this.state.phone}
handleChange={this.handleChange}
/>
<FormField label="Email" help="" error={this.state.emailError}>
<TextInput
name="email"
value={this.state.email}
placeHolder="Required in order to login"
onDOMChange={this.checkEmail}
/>
</FormField>
</Form>
);
}
}
export default compose(
graphql(PersonSave, { name: 'PersonSave' }),
graphql(Organizations, { name: 'OrganizationList' }),
)(PersonForm);
And the Phone Child:
import React, { Component } from 'react';
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
import FormField from 'grommet/components/FormField';
import Notification from 'grommet/components/Notification';
import TextInput from 'grommet/components/TextInput';
const Unique = gql`
mutation Unique(
$phone: String) {
unique(
phone: $phone) {
id
}
}`;
class Phone extends Component {
constructor(props) {
super(props);
this.state = {
phone: this.props.phone,
intl: this.props.phone,
inUse: false,
phoneError: undefined,
};
this.checkPhone = this.checkPhone.bind(this);
}
checkPhone(event) {
const name = event.target.name;
const value = event.target.value.replace(/[^0-9]+/g, '');
let intl = value;
if (intl.charAt(0) === '0') {
intl = `+44${intl.substring(0)}`;
} else {
intl = `+1${intl}`;
}
this.setState({
[name]: value,
intl,
phoneError: value.length !== 10 && 'Please enter 10 digits including area code',
});
this.props.handleChange({ target: {
name: 'phone',
value: value.length === 10 ? intl : undefined },
});
this.props.mutate({
variables: {phone},
}).then((result) => {
console.log(result);
});;
}
render() {
return (
<FormField label="Phone" error={this.state.phoneError}>
<TextInput
id={'phone'}
name="phone"
value={this.state.phone}
placeHolder="Phone number including area code"
onDOMChange={this.checkPhone}
/>
</FormField>
);
}
}
export default graphql(Unique)(Phone);
@oakmad sorry i cant see anything wrong with your code, unfortunately - unless the client singleton is not setup right but then none of it would work.
Thanks @farzd - It seems to be working without issue elsewhere in the app, so I presume the client is OK. I'm relatively new to react and apollo (from Meteor) and suspect I've made some news error. I'll revisit it in future as I get more experience.
@oakmad I know this isn't helpful in any way, but I just started running into this issue today and I have no idea why. I'll report back if I figure it out, but it's definitely nothing to do with conditional rendering.
EDIT: It was after lunch and my brain wasn't working, all I had to do was mock the provider because it was failing tests but running correctly in the app.
This is an issue for me as well. I think it's due to the fact that the component trying to use @withApollo is created as a property to a parent component. That's my hunch, at least.
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions to Apollo Client!
+1
i having the exact issue
I had this issue when I introduced server side rendering to an app. Here's how the problematic code was setup:
...
import DisplayComponent from './DisplayComponent';
const client = new ApolloClient({ ...config });
function MyComponent() {
return (
<DisplayComponent
queryVal="foo"
/>
)
}
ReactDOM.render(
<ApolloProvider client={client}>
<MyComponent />
</ApolloProvider>,
document.getElementById('mount-div-id'),
);
export default MyComponent;
I got the error that is in the title of the issue. I fixed it by updating my code to this:
...
import DisplayComponent from './DisplayComponent';
const client = new ApolloClient({ ...config });
function MyComponent() {
return (
<ApolloProvider client={client}>
<DisplayComponent
queryVal="foo"
/>
</ApolloProvider>
)
}
ReactDOM.render(
<MyComponent />,
document.getElementById('mount-div-id'),
);
export default MyComponent;
Hopefully that helps someone.
i guess you can now just use <ApolloConsumer>
_Edit: This does not seem to work anymore. Move along. But sure, go visit the link if you're curious._
In case you got this error while using react-apollo-hooks
, you may want to take a look at this sandbox: https://codesandbox.io/s/vnr2lqvrm0.
In case you got this error while using
react-apollo-hooks
, you may want to take a look at this sandbox: https://codesandbox.io/s/vnr2lqvrm0.
You are a life saving, hours saved!!
In case you got this error while using
react-apollo-hooks
, you may want to take a look at this sandbox: https://codesandbox.io/s/vnr2lqvrm0.
I am using react-apollo-hooks and had the components set up just like the sandbox (Root, not BuggyRoot), but still got the error.
Reverting back to 2.5.2 'fixed' it for now. https://github.com/apollographql/react-apollo/issues/2900
Ditto, having issues with 2.5.6, fixed it after reverting to 2.5.2
I got this error when trying to use @apollo/react-hooks
The solution as suggested by @sampathsris is to wrap your app with both ApolloProvider
from both the new hooks lib and the original react-apollo
lib
import { ApolloProvider } from 'react-apollo'
import { ApolloProvider as ApolloHooksProvider } from '@apollo/react-hooks'
<ApolloProvider client={client}>
<ApolloHooksProvider client={client}>
{/* App here! */}
</ApolloHooksProvider>
</ApolloProvider>
Have the same problem with react-apollo 3.0.0 and 3.0.1. Recipe @ptimson didn't work for me.
2.5.2 works for me, 3.0.0 does not
2.5.2 worked for me too. But I didn't used react-apollo, solved it by creating HOC on hooks for classes)).
import React from 'react';
import { useQuery } from '@apollo/react-hooks';
export const Query = ({children, query, variables}) => {
const graphqlState = useQuery(query, variables);
return (
<div>
{
React.Children.map(children, child =>
React.cloneElement(child, { ...graphqlState })
)
}
</div>
)
};
And then use it:
import React, { Component } from 'react';
import gql from 'graphql-tag';
import { Query } from '@/utils/withApollo';
import MaterialsTable from '@/components/MaterialsTable';
const GET_CONTENT_UNITS = gql`
query GetContentUnits($input: ContentUnitFilterInput) {
getContentUnits(input: $input) {
name
id
cover
price
}
}
;
export default class Dashboard extends Component {
render() {
return (
<div>
<h1>Dashboard</h1>
<Query query={GET_CONTENT_UNITS}>
<MaterialsTable />
</Query>
</div>
);
}
}
Had the same issue, aparently you cant use tags and hooks at the same time. If you use hooks, dont use tags. Also, ApolloProvider should be imported from @apollo/react-hooks instead of "react-apollo"
Tried with react-apollo too, no luck :( @ptimson
"@apollo/react-hooks": "3.0.0",
"apollo-boost": "^0.4.7",
"graphql": "^14.5.8",
Used all the version combinations from 3.0.0 to 3.1.x same error msg "
Unhandled Rejection (Invariant Violation): Could not find "client" in the context or passed in as an option. Wrap the root component in an
Doc says we should install @apollo/react-hooks and import ApolloProvider, none of this are working,
I am just trying to setup hello world project for apollo client :( any one have boilerplate or working version combinations, Please share it.
Thanks!
Following these instructions: https://www.apollographql.com/docs/react/get-started/ I was dismayed when the error "Uncaught ReferenceError: client is not defined" showed up -- and I had exactly copied their code...
import React from 'react';
import { render } from 'react-dom';
import { ApolloProvider } from '@apollo/react-hooks';
const App = () => (
<ApolloProvider client={client}>
<div>
<h2>My first Apollo app 🚀</h2>
</div>
</ApolloProvider>
);
render(<App />, document.getElementById('root'));
It took a while before I realized that they left out the client definition in their ApolloProvider example...
It works once you bring the client definition in:
import React from 'react';
import { render } from 'react-dom';
import { ApolloProvider } from '@apollo/react-hooks';
import ApolloClient from 'apollo-boost';
const App = () => {
const client = new ApolloClient({
uri: 'https://48p1r2roz4.sse.codesandbox.io',
});
return (
<ApolloProvider client={client}>
<div>
<h2>My first Apollo app 🚀</h2>
</div>
</ApolloProvider>
);
};
render(<App />, document.getElementById('root'));
cheers,
Al;
I got this error when trying to use
@apollo/react-hooks
The solution as suggested by @sampathsris is to wrap your app with both
ApolloProvider
from both the new hooks lib and the originalreact-apollo
libimport { ApolloProvider } from 'react-apollo' import { ApolloProvider as ApolloHooksProvider } from '@apollo/react-hooks' <ApolloProvider client={client}> <ApolloHooksProvider client={client}> {/* App here! */} </ApolloHooksProvider> </ApolloProvider>
Why does this solution work? it feels wrong to have to import two different providers? can someone explain please.
I am now using the useQuery hook (it ROCKS!)
wrapping thusly:
import { ApolloProvider } from 'react-apollo-hooks';
import ApolloClient from 'apollo-boost';
const client = new ApolloClient({
uri: process.env.BACK_END_URL,
headers: { authorization: `Bearer ${process.env.READ_ONLY_JWT}` },
});
return (
<ApolloProvider client={client}>
{/* App here! */}
</ApolloProvider>
and consuming thusly:
import gql from 'graphql-tag';
import { useQuery } from 'react-apollo-hooks';
export function ContactListView({ configuration, history, match }) {
const presentersQuery = gql`
{
data: findEventPresenters(eventSerial: "${configuration.serial}") {
contact { id name email phone contact_type_id }
}
}
`;
const contactTypeQuery = gql`
{
data: findContactType(name: "${match.params.kind}") {
id name
}
}
`;
const {
data: contactType,
error: contactTypeError,
loading: contactTypeLoading,
} = useQuery(contactTypeQuery);
const {
data: presenters,
error: presentersError,
loading: presentersLoading,
} = useQuery(presentersQuery);
if (contactTypeLoading || presentersLoading) {
return <LoadingIndicator />;
}
if (contactTypeError || presentersError) {
return <Error>{contactTypeError || presentersError}</Error>;
}
const contacts = presenters.data
.map(c => c.contact)
.map(c => {
c.contactTypeName = titleCase(contactType.data.name);
return c;
})
.filter(c => c.contact_type_id === contactType.data.id);
const contactListProps = { contacts };
[ and so on.. ]
I found that I had accidentally installed a version of @apollo/react-common that was 3.1.3 but @apollo/react-hooks needs 3.1.4 and @apollo/react-hooks has its own copy in its install dir--hence it can get out of sync.
So there was a mismatch.
I manually removed the 3.1.3 version and a few other apollo libs that had accumulated independently of the dependencies from hooks, reinstalled @apollo/react-hooks and that cleared it up for me.
In case anyone else stumble on this, yarn why @apollo/react-common
can help you figure out why you have different version of <ApolloProvider>
used by different packages.
This might work
rm -rf node_modules package-lock.json
npm install
Maybe there is some issue with npm cache, if it still doesn't work try
npm cache clean --force
Note: this will clean all your your node dependencies, however the package.json file is not deleted. Use these commands at own risk.
Is anyone else running into this when trying to run the official docs demo for hooks? From what I understand, everything has been now bundled into @apollo/client
. Is that correct? I'm running "@apollo/client": "^3.0.2""
@Kallirroi I am also currently attempting this with "@apollo/client": "^3.0.2",
and after going through this thread, I'm more confused than ever. I got to this error when attempting to use the useLazyQuery hook, and after attempting the recipe offered by @ptimson I had no luck. Please report back if you find anything as this appears to still cause some issues.
keep the version of @apollo/react-hooks as same as the version of react-apollo
"@apollo/react-hooks": "^3.1.5",
"react-apollo": "^3.1.5"
I have used the latest version following the official docs with "@apollo/client": "^3.2.3", and I went through the same problem.
I have used the latest version following the official docs with "@apollo/client": "^3.2.3", and I went through the same problem.
same here. i'm on version 3.3.2
.
it actually only happens on certain components for me. I have the whole app wrapped with the ApolloProvider
though.
Havin same issue I am on 3.1.5
@ahmedbrandver I fixed my issue, what was happening to me was that I using the hooks from both @apollo/client
and @apollo/react-hooks
. What I did to fix it was remove the @apollo/react-hooks
library and just import the hooks or anything GraphQL related from @apollo/client
.
@hanselabreu this fixed it for me, nice one.
Most helpful comment
I got this error when trying to use
@apollo/react-hooks
The solution as suggested by @sampathsris is to wrap your app with both
ApolloProvider
from both the new hooks lib and the originalreact-apollo
lib