Rendered more hooks than during the previous render - react-hooks

How to use 2 graphql queries with react-apollo-hooks where the 2nd query depends on a parameter retrieved from the 1st query?
I try to use 2 queries which looks like this:
const [o, setO] = useState()
const { loading: loadingO, error: errorO, data: dataO } = useQuery(Q_GET_O, { onCompleted: d => setO(d.getO[0].id) });
if (loadingO) { return "error" }
const { loading: loadingOP, error: errorOP, data: dataOP } = useQuery(Q_GET_OP, { variables: { o } })
However, when I run my project, react-hooks gives me the following message:
"index.js:1437 Warning: React has detected a change in the order of Hooks called by Upgrade. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks"
I would like to know how I can use react-apollo-hooks in order to run a query that depends on another query. It works great if the graphql query variables are known in advance. However, I did not find a solution for variables that come from other query.

The problem here is that you are short circuit returning before all of your hooks have a chance to run.
React will complain if you exit a render function before all of the hooks have a chance to be called.
For example:
function BrokenFoo () {
const query = useSomeQuery();
if (query.loading) return <Loading />
// This will cause some issues because
// it's possible that we return before our useState hook gets called
const [bar, setBar] = useState();
return <SomeComponent bar={bar} setBar={setBar} data={query.data} />
}
To fix:
function FixedFoo () {
// This will be fine because
// all of the hooks have a chance to be called before a return
const query = useSomeQuery();
const [bar, setBar] = useState();
if (query.loading) return <Loading />
return <SomeComponent bar={bar} setBar={setBar} data={query.data} />
}

You can add the skip option to the second query and lose the if condition:
const { loading: loadingOP, error: errorOP, data: dataOP }
= useQuery(Q_GET_OP, { variables: { o }, skip: !o })
from the docs:
If skip is true, the query will be skipped entirely

Related

graphql / Apollo test case fails Error: Expected one matching operation for criteria "Match DocumentNode", found none

I am trying to write a test for an angular service which I am using with graphql & Apollo.
I'm receiving these errors: Error: Expected one matching operation for criteria "Match DocumentNode", found none.
and
Error: Expected no open operations, found 1:
foo.spec.ts
import { TestBed } from '#angular/core/testing';
import {
....
const fragment: DocumentNode = gql`
fragment SummaryDetails on SummaryDetails {
foo
...
}
`;
const summaryQuery: DocumentNode = gql`
query Summary(
) {
Summary(
) {
...SummaryDetails
}
}
${fragment}
`;
const fundDataServiceParams: FundDataServiceParams = {
foo ...
};
const expectedRawSummaryDetails: any = {
Summary: [
{
foo ...
},
],
};
const expectedSummaryDetails: SummaryDetail[] = [
{
foo ...
},
];
describe('FundSummaryServiceRegisterMethod', () => {
let controller: ApolloTestingController;
let fundSummaryService: FundSummaryService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ApolloTestingModule, HttpClientTestingModule],
});
controller = TestBed.inject(ApolloTestingController);
foo = TestBed.inject(foo);
});
afterEach(() => {
controller.verify();
});
fit('should return foodetails', (done: DoneFn) => {
fundSummaryService
.register(fragment, fundDataServiceParams)
.subscribe((foo) => {
expect(foo).toEqual(foo);
done();
});
const op = controller.expectOne(fooQuery);
expect(op.operation.variables.foo).toEqual(foo.foo);
op.flushData(expectedfoo);
});
});
Note: I tried this old post's suggestion, didn't work.
The good news for you is that in the afterEach, controller.verify() is failing meaning there is a query in queue and not all of them have been dealt with. I am thinking that your summaryQuery is slightly off where it is not matching exactly the query where the afterEach is saying is still in queue and has not been flushed.
I think you can use a different definition of expectOne from the documentation to match the query in queue. I don't have much experience with Apollo or GraphQL but try something like this for the expectOne:
const op = controller.expectOne(operation => {
// can assert some stuff on the operation like the documentation shows
return true;
});
If the above works, it most likely means that summaryQuery does not match the query that ApolloTestingController sees.

Apollo GraphQL Deconstruction of data not working

I am digging graphql so I followed a tutorial, And I stucked in this part.
Home.js
function Home() {
const {
loading,
data: { getPosts: posts } // <===## Here ##
} = useQuery(FETCH_POSTS_QUERY);
return (
<div>
{loading ? (
<h1>Loading posts..</h1>
) : (
posts &&
posts.map((post) => (
<p>
{post.content}
</p>
))
)}
</div>
);
}
const FETCH_POSTS_QUERY = gql`
{
getPosts {
id
content
}
}
`;
export default Home;
resolver
Query: {
async getPosts() {
try {
const posts = await Post.find().sort({ createdAt: -1 });
return posts;
} catch (err) {
throw new Error(err);
}
}
},
Whole code: https://github.com/hidjou/classsed-graphql-mern-apollo/tree/react10
In above example is working well, and it use it use data: { getPosts: posts } for deconstruction of returned data. but In my code, I followed it but I got an error
TypeError: Cannot read property 'getPosts' of undefined
Instead, If I code like below,
function Home() {
const {
loading,
data // <===## Here ##
} = useQuery(FETCH_POSTS_QUERY);
if(loading) return <h1>Loading...</h1>
const { getPosts: posts } = data // <===## Here ##
return (
<div>
{loading ? (
<h1>Loading posts..</h1>
) : (
posts &&
posts.map((post) => (
<p>
{post.content}
</p>
))
)}
</div>
);
}
It working well. Seems like my code try to reference data before it loaded. But I don't know why this happen. Code is almost same. Different things are 1. my code is on nextjs, 2. my code is on apollo-server-express. Other things are almost same, my resolver use async/await, and will return posts. Am I miss something?
my resolver is like below.
Query: {
async getPosts(_, { pageNum, searchQuery }) {
try {
const perPage = 5
const posts =
await Post
.find(searchQuery ? { $or: search } : {})
.sort('-_id')
.limit(perPage)
.skip((pageNum - 1) * perPage)
return posts
} catch (err) {
throw new Error(err)
}
},
Your tutorial may be out of date. In older versions of Apollo Client, data was initially set to an empty object. This way, if your code accessed some property on it, it wouldn't blow up. While this was convenient, it also wasn't particularly accurate (there is no data, so why are we providing an object?). Now, data is simply undefined until your operation completes. This is why the latter code is working -- you don't access any properties on data until after loading is false, which means the query is done and data is no longer undefined.
If you want to destructure data when your hook is declared, you can utilize a default value like this:
const {
loading,
data: { getPosts: posts } = {}
} = useQuery(FETCH_POSTS_QUERY)
You could even assign a default value to posts as well if you like.
Just keep in mind two other things: One, data will remain undefined if a network error occurs, even after loading is changed to true, so make sure your code accounts for this scenario. Two, depending on your schema, if there's errors in your response, it's possible for your entire data object to end up null. In this case, you'll still hit an issue with destructuring because default values only work with undefined, not null.

Apollo client useQuery not updating data after useMutation

Using this mutation:
import produce from 'immer
const [createItem] = useMutation(CREATE_ITEM, {
update (client, { data: { createItem } }) {
const queryResults = client.readQuery({
query: GET_LATEST_ORDER,
variables: { orderDepth: 1 }
})
client.writeQuery({
query: GET_LATEST_ORDER,
variables: { orderDepth: 1 },
data: produce(queryResults, draft => {
draft.orders[0].items.push(createItem)
})
})
}
})
I am unable to get
const { loading, data, refetch } = useQuery(GET_LATEST_ORDER, {
variables: { orderDepth: 1 }
})
to show updated data after the mutation.
The apollo cache is updated correctly. But data on the useQuery does not change.
The issue ended up being the returned object from the mutation was not exactly the same. It was missing an #client field.
While obvious in hindsight no where I searched described this as a reason except for a comment I saw mentioning perhaps missing the __typename.
This would have been obvious had apollo thrown an error. However, no error was thrown, nor existed on the useQuery.

graphql after running mutation if I quickly goback to Previous page, occur error

after running mutation using the graphql, if I quickly goback to Previous page,
occur error : Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and
asynchronous tasks in %s.%s, a useEffect cleanup function,
I think it's because I quickly go to another page during the mutation.
If this is not the case, there is no error.
(Even if an error occurs, update succeeds. but I'm worried about errors)
Even if move to another page during mutating, I want to proceed with the update as it is
How can I proceed with the update?
if If there is no way, is there method that How to create a delay during mutating
im so sorry. my english is not good.
const CalendarTodo = ({
month,
day,
data,`enter code here`
isImportWhether,
setIsImportWhether
}) => {
const [value, setValue] = useState("");
const monthDay = `${month + 1}월 ${day}일`;
const [createToDoMutation] = useMutation(CREATE_TODO, {
variables: {
toDoId:
data &&
data.toDos &&
data.toDos.filter(object => object.monthDay === monthDay)[0] &&
data.toDos.filter(object => object.monthDay === monthDay)[0].id,
monthDay: monthDay,
dayToDo: value,
importEvent: isImportWhether
},
update: (proxy, { data: { createToDo } }) => {
const data = proxy.readQuery({ query: SEE_TODO_OF_ME });
data &&
data.toDos &&
data.toDos.filter(object => object.monthDay === monthDay)[0] &&
data.toDos
.filter(object => object.monthDay === monthDay)[0]
.dayToDo.push(createToDo);
proxy.writeQuery({ query: SEE_TODO_OF_ME, data });
},
optimisticResponse: {
createToDo: {
__typename: "DayToDo",
id: Math.random().toString(),
toDoList: value,
importEvent: isImportWhether
}
}
});
return (
<>
);
};
export default CalendarTodo;
As you already guessed the reason is the asynchronous request that keeps on running even after un-mounting the component due to navigating away from it.
There are many ways to solve this. One is to add a check whether or not the component you are calling the async request from is still mounted and only update its state if so, e.g.:
useEffect(() => {
let isMounted = true;
apollo.mutate({query, variables, update: {
if(isMounted) {
// update state or something
}
})
return () => {
isMounted = false;
};
}, []);
This way however the data might be lost. If you want to make sure that you receive and store the return value you should add the request to a higher level component or context hat will not be unmounted on navigation. This way you can trigger the async call but dont have to worry about navigating away.

Using graphql-tools to mock a GraphQL server seems broken

I've followed the documentation about using graphql-tools to mock a GraphQL server, however this throws an error for custom types, such as:
Expected a value of type "JSON" but received: [object Object]
The graphql-tools documentation about mocking explicitly states that they support custom types, and even provide an example of using the GraphQLJSON custom type from the graphql-type-json project.
I've provided a demo of a solution on github which uses graphql-tools to successfully mock a GraphQL server, but this relies on monkey-patching the built schema:
// Here we Monkey-patch the schema, as otherwise it will fall back
// to the default serialize which simply returns null.
schema._typeMap.JSON._scalarConfig.serialize = () => {
return { result: 'mocking JSON monkey-patched' }
}
schema._typeMap.MyCustomScalar._scalarConfig.serialize = () => {
return mocks.MyCustomScalar()
}
Possibly I'm doing something wrong in my demo, but without the monkey-patched code above I get the error regarding custom types mentioned above.
Does anyone have a better solution than my demo, or any clues as to what I might be doing wrong, and how I can change the code so that the demo works without monkey-patching the schema?
The relevant code in the demo index.js is as follows:
/*
** As per:
** http://dev.apollodata.com/tools/graphql-tools/mocking.html
** Note that there are references on the web to graphql-tools.mockServer,
** but these seem to be out of date.
*/
const { graphql, GraphQLScalarType } = require('graphql');
const { makeExecutableSchema, addMockFunctionsToSchema } = require('graphql-tools');
const GraphQLJSON = require('graphql-type-json');
const myCustomScalarType = new GraphQLScalarType({
name: 'MyCustomScalar',
description: 'Description of my custom scalar type',
serialize(value) {
let result;
// Implement your own behavior here by setting the 'result' variable
result = value || "I am the results of myCustomScalarType.serialize";
return result;
},
parseValue(value) {
let result;
// Implement your own behavior here by setting the 'result' variable
result = value || "I am the results of myCustomScalarType.parseValue";
return result;
},
parseLiteral(ast) {
switch (ast.kind) {
// Implement your own behavior here by returning what suits your needs
// depending on ast.kind
}
}
});
const schemaString = `
scalar MyCustomScalar
scalar JSON
type Foo {
aField: MyCustomScalar
bField: JSON
cField: String
}
type Query {
foo: Foo
}
`;
const resolverFunctions = {
Query: {
foo: {
aField: () => {
return 'I am the result of resolverFunctions.Query.foo.aField'
},
bField: () => ({ result: 'of resolverFunctions.Query.foo.bField' }),
cField: () => {
return 'I am the result of resolverFunctions.Query.foo.cField'
}
},
},
};
const mocks = {
Foo: () => ({
// aField: () => mocks.MyCustomScalar(),
// bField: () => ({ result: 'of mocks.foo.bField' }),
cField: () => {
return 'I am the result of mocks.foo.cField'
}
}),
cField: () => {
return 'mocking cField'
},
MyCustomScalar: () => {
return 'mocking MyCustomScalar'
},
JSON: () => {
return { result: 'mocking JSON'}
}
}
const query = `
{
foo {
aField
bField
cField
}
}
`;
const schema = makeExecutableSchema({
typeDefs: schemaString,
resolvers: resolverFunctions
})
addMockFunctionsToSchema({
schema,
mocks
});
// Here we Monkey-patch the schema, as otherwise it will fall back
// to the default serialize which simply returns null.
schema._typeMap.JSON._scalarConfig.serialize = () => {
return { result: 'mocking JSON monkey-patched' }
}
schema._typeMap.MyCustomScalar._scalarConfig.serialize = () => {
return mocks.MyCustomScalar()
}
graphql(schema, query).then((result) => console.log('Got result', JSON.stringify(result, null, 4)));
I and a few others are seeing a similar issue with live data sources (in my case MongoDB/Mongoose). I suspect it is something internal to the graphql-tools makeExecutableSchema and the way it ingests text-based schemas with custom types.
Here's another post on the issue: How to use graphql-type-json package with GraphQl
I haven't tried the suggestion to build the schema in code, so can't confirm whether it works or not.
My current workaround is to stringify the JSON fields (in the connector) when serving them to the client (and parsing on the client side) and vice-versa. A little clunky but I'm not really using GraphQL to query and/or selectively extract the properties within the JSON object. This wouldn't be optimal for large JSON objects I suspect.
If anyone else comes here from Google results, the solution for me was to add the JSON resolver as parameter to the makeExecutableSchema call. It's described here:
https://github.com/apollographql/apollo-test-utils/issues/28#issuecomment-377794825
That made the mocking work for me.

Resources