question
stringlengths
11
28.2k
answer
stringlengths
26
27.7k
tag
stringclasses
130 values
question_id
int64
935
78.4M
score
int64
10
5.49k
I've been searching for days on how to layout a rundeck workflow with job dependencies. what I need to do is to have 3 jobs: job-1 and job-2 are scheduled to run in parallel while job-3 will only be triggered after the completion of both job-1, and job-2. assuming that job-1 and job-2 have different execution times. I ...
You can achieve this by compiling a master job which includes 2 steps: step: job-1 and job-2 as a sub-job which includes both (run in parallel if node oriented execution is selected) step: job-3 But not all 3 in in the same flow.
Rundeck
36,291,321
13
I'm attempting to set up Apollo GraphQL support in a new React project, but when I try to compile a query using gql I keep receiving the error: Syntax Error: Expected Name, found } This is generated by the following code: import gql from 'graphql-tag' const query = gql` { user(id: 5) { firstName ...
This error occurs mostly when there are unclosed curly braces or when some fields are not properly defined while calling the query.
Apollo
48,331,103
92
I don't have any previous experience with *MQs and I'm looking to build knowledge on JMS and message queues in general. That way, I wonder whether I should start with ActiveMQ or just "ignore" it altogether and start by teaching myself Apollo. Is Apollo as feature-complete as ActiveMQ? Does it implement JMS 2.0 (I see ...
Apache ActiveMQ is a great workhorse full of features and nice stuff. It's not the fastest MQ software around but fast enough for most use cases. Among features are flexible clustring, fail-over, integrations with different application servers, security etc. Apache Apollo is an attempt to write a new core for ActiveMQ ...
Apollo
27,666,943
71
I'm learning GraphQL now and while walking through tutorial I met behavior that I can't understand. Let's say we have defined type in schema: type Link { id: ID! url: String! description: String! postedBy: User votes: [Vote!]! } Due to docs votes: [Vote!]! means that that field should be a non-nullable and ...
Non-null means exactly what it sounds like -- not null. An empty array is not null -- it's still returning a value. Here is a summary table: declaration accepts: | null | [] | [null] | [{foo: 'BAR'}] ------------------------------------------------------------------------ [Vote!]! | no | yes | no |...
Apollo
46,770,501
69
How do you prevent a nested attack against an Apollo server with a query such as: { authors { firstName posts { title author { firstName posts{ title author { firstName posts { title [n author] ...
As of the time of writing, there isn't a built-in feature in GraphQL-JS or Apollo Server to handle this concern, but it's something that should definitely have a simple solution as GraphQL becomes more popular. This concern can be addressed with several approaches at several levels of the stack, and should also always ...
Apollo
37,337,466
64
Is it possible to have a define a field as Date or JSON in my graphql schema ? type Individual { id: Int name: String birthDate: Date token: JSON } actually the server is returning me an error saying : Type "Date" not found in document. at ASTDefinitionBuilder._resolveType (****node_modules\graphql\ut...
Have a look at custom scalars: https://www.apollographql.com/docs/graphql-tools/scalars.html create a new scalar in your schema: scalar Date type MyType { created: Date } and create a new resolver: import { GraphQLScalarType } from 'graphql'; import { Kind } from 'graphql/language'; const resolverMap = { ...
Apollo
49,693,928
60
Let's say my graphql server wants to fetch the following data as JSON where person3 and person5 are some id's: "persons": { "person3": { "id": "person3", "name": "Mike" }, "person5": { "id": "person5", "name": "Lisa" } } Question: How to create the schema type definition with apollo? The keys p...
GraphQL relies on both the server and the client knowing ahead of time what fields are available available for each type. In some cases, the client can discover those fields (via introspection), but for the server, they always need to be known ahead of time. So to somehow dynamically generate those fields based on the ...
Apollo
46,562,561
48
I was going through the documentation of Apollo React hooks. And saw there are two queries hooks to use for which is useQuery and useLazyQuery I was reading this page. https://www.apollographql.com/docs/react/api/react/hooks/ Can someone explain me what is the difference between them and in which case it should be used...
When useQuery is called by the component, it triggers the query subsequently. But when useLazyQuery is called, it does not trigger the query subsequently, and instead return a function that can be used to trigger the query manually. It is explained on this page: https://www.apollographql.com/docs/react/data/queries/#ma...
Apollo
63,681,650
45
I have a queries file that looks like this: import {gql} from 'react-apollo'; const queries = { getApps: gql` { apps { id name } } `, getSubjects: gql` { subjects { id name } } ` }; export default queries; I then import this file to my R...
My preferred way is to use the compose functionality of the apollo client (docu). EDIT: If you have more than one query you should name them. So in your case, it could look like this: import React, {Component} from 'react' import queries from './queries' import { graphql, compose } from 'react-apollo'; class Tes...
Apollo
43,380,704
44
I tried changing the addTypeName: false in the Apollo client in GraphQL apollo.create({ link: httpLinkWithErrorHandling, cache: new InMemoryCache({ addTypename: false }), defaultOptions: { watchQuery: { fetchPolicy: 'network-only', errorPolicy: 'all' } } But it works and it throws the follo...
Cleaning Unwanted Fields From GraphQL Responses In the above thread, I have posted the answer for this problem please refer to it
Apollo
55,259,856
42
If I have a set of field that is common to multiple types in my GraphQL schema, is there a way to do something like this? type Address { line1: String city: String state: String zip: String } fragment NameAndAddress on Person, Business { name: String address: Address } type Business { ...NameAndAddres...
Fragments are only used on the client-side when making requests -- they can't be used inside your schema. GraphQL does not support type inheritance or any other mechanism that would reduce the redundancy of having to write out the same fields for different types. If you're using apollo-server, the type definitions that...
Apollo
48,940,240
41
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 vi...
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 GitHu...
Apollo
58,475,780
39
I am using the apollo-client library to query data from my Graphql server. Some of the queries are sent to the server every 5 seconds through apollo polling ability. Is there a generic way to add a custom header to all requests that are sent by my polling client?
Two Solutions There are two ways to do that. One is quick and easy and will work for a specific query with some limitation, and the other is a general solution that is safer and can work for multiple queries. Quick and Easy Solution Advantages it's quick and... easy When you configure your query you can configure it ...
Apollo
48,558,681
35
I am currently loading the GraphQL schema using a separate .graphql file, but it is encapsulated within strings: schema.graphql const schema = ` type CourseType { _id: String! name: String! } type Query { courseType(_id: String): CourseType courseTypes: [CourseType]! } ` module.exports = schem...
If you define your type definitions inside a .graphql file, you can read it in one of several ways: 1.) Read the file yourself: const { readFileSync } = require('fs') // we must convert the file Buffer to a UTF-8 string const typeDefs = readFileSync(require.resolve('./type-defs.graphql')).toString('utf-8') 2.) Utiliz...
Apollo
62,290,875
35
I am using a watchQuery or query in Apollo-Angular (graphql) How is the logic and difference of the watchQuery and query
query is something you just query for once, you can consider it as an equivalent of GET. watchQuery is something you constantly keep a watch on query, whenever that query will be refetched or the data related to that query is changed from anywhere else, this method will keep on emitting the updated data. It's really si...
Apollo
49,618,392
33
Apollo link offers an error handler onError Issue: Currently, we wish to refresh oauth tokens when they expires during an apollo call and we are unable to execute an async fetch request inside the onError properly. Code: initApolloClient.js import { ApolloClient } from 'apollo-client'; import { onError } from 'apollo...
I'm refreshing the token this way (updated OP's): import { ApolloClient } from 'apollo-client'; import { onError } from 'apollo-link-error'; import { ApolloLink, Observable } from 'apollo-link'; // add Observable // Define Http link const httpLink = new createHttpLink({ uri: '/my-graphql-endpoint', credentials: '...
Apollo
50,965,347
33
I am building an application using: MySQL as the backend database Apollo GraphQL server as a query layer for that database Sequelize as the ORM layer between GraphQL and MySQL As I am building out my GraphQL schema I'm using the GraphQL ID data type to uniquely identify records. Here's an example schema and its MySQL...
ID is a scalar type described in the GraphQL specification (working draft October 2016): The ID type is serialized in the same way as a String; however, it is not intended to be human‐readable. While it is often numeric, it should always serialize as a String. Your observation I can use GraphQL to query the MySQL d...
Apollo
47,874,344
32
I am using Apollo Client for the frontend and Graphcool for the backend. There are two queries firstQuery and secondQuery that I want them to be called in sequence when the page opens. Here is the sample code (the definition of TestPage component is not listed here): export default compose( graphql(firstQuery, ...
The props added by your firstQuery component will be available to the component below (inside) it, so you can do something like: export default compose( graphql(firstQuery, { name: 'firstQuery' }), graphql(secondQuery, { name: 'secondQuery', skip: ({ firstQuery }) => !firstQuery.data, options: ({...
Apollo
49,317,582
31
I want to define a mutation using graphql. My mutation is getting an object as argument. So I defined the new Object in the schema and in the resolver using GraphQLObjectType. However I m getting this error : Error: Agreement.name defined in resolvers, but not in schema Any idea ? Here is my Schema definition const...
Couple of things to fix here. First, to use an object as an argument, you have to define it as an input (or GraphQLInputObjectType) in your schema -- you cannot use a regular type (or GraphQLObjectType) as an argument. So your type definitions need to look something like this: type Mutation { agreementsPost(agreement...
Apollo
49,990,427
31
Just a basic apollo query request this.client.query({ query: gql` { User(okta: $okta){ id } }` }).then(result => { this.setState({userid: result.data.User}); console.log(this.state.userid.id) }).catch(error => { this.setState({error: <Alert color="danger">Error</Alert>}); }); The qu...
It should be something like this: const query = gql` query User($okta: String) { User(okta: $okta){ id } } `; client.query({ query: query, variables: { okta: 'some string' } }) The documentation for Apollo client with all the details can be found here: https://www.apollographql.com/docs/re...
Apollo
51,522,902
30
I am working in Apollo, GraphQL and Nuxtjs project, when setting up Apollo configuration I got this Warning: link.js:38 Error: You are calling concat on a terminating link, which will have no effect at new LinkError (linkUtils.js:41) at concat (link.js:38) at ApolloLink.webpackJsonp../node_modules/apollo-link/lib/link....
The solution for me is putting Http Link at the end of the Apollo Link array (used when you're creating the Apollo Client). ... const param = { link: ApolloLink.from([ onError(...) =>..., authLink..., new HttpLink({ uri: '/graphql', credentials: 'same-origin' }) ]), cache: ..., conne...
Apollo
51,840,201
30
graphql schema like this: type User { id: ID! location: Location } type Location { id: ID! user: User } Now, the client sends a graphql query. Theoretically, the User and Location can circular reference each other infinitely. I think it's an anti-pattern. For my known, there is no middleware or way to limit t...
It depends. It's useful to remember that the same solution can be a good pattern in some contexts and an antipattern in others. The value of a solution depends on the context that you use it. — Martin Fowler It's a valid point that circular references can introduce additional challenges. As you point out, they are a ...
Apollo
53,863,934
28
I'm having a trouble with Graphql and Apollo Client. I always created different responses like 401 code when using REST but here I don't know how to do a similar behavior. When I get the response, I want it to go to the catch function. An example of my front-end code: client.query({ query: gql` query TodoApp { ...
The way to return errors in GraphQL (at least in graphql-js) is to throw errors inside the resolve functions. Because HTTP status codes are specific to the HTTP transport and GraphQL doesn't care about the transport, there's no way for you to set the status code there. What you can do instead is throw a specific error ...
Apollo
42,937,502
27
Currently I have a useLazyQuery hook which is fired on a button press (part of a search form). The hook behaves normally, and is only fired when the button is pressed. However, once I've fired it once, it's then fired every time the component re-renders (usually due to state changes). So if I search once, then edit th...
You don't have to use async with the apollo client (you can, it works). But if you want to use useLazyQuery you just have to pass variables on the onClick and not directly on the useLazyQuery call. With the above example, the solution would be: function DelayedQuery() { const [dog, setDog] = useState(null); const [...
Apollo
57,499,553
27
I have an Apollo GraphQL server and I have a mutation that deletes a record. This mutation receives the UUID of the resource, calls a REST (Ruby on Rails) API and that API just returns an HTTP code of success and an empty body (204 No Content) when the deletion was successful and an HTTP error code with an error messag...
A field in GraphQL must always have a type. GraphQL has the concept of null but null is not itself a type -- it simply represents the lack of value. There is no "void" type in GraphQL. However, types are nullable by default, so regardless of a field's type, your resolver can return nothing and the field will simply res...
Apollo
58,889,341
24
I was thinking about ways of implementing graphql response that would contain both an error and data. Is it possible to do so without creating a type that would contain error? e.g. Mutation addMembersToTeam(membersIds: [ID!]! teamId: ID!): [Member] adds members to some team. Suppose this mutation is called with the fol...
Is it possible to solve this problem without adding error field to the return type? Unfortunately, no. A resolver can either return data, or return null and throw an error. It cannot do both. To clarify, it is possible to get a partial response and some errors. A simple example: const typeDefs = ` type Query { ...
Apollo
52,778,096
22
this is my first discussion post here. I have learned Apollo + GraphQL through Odyssey. Currently, I am building my own project using Next.js which required fetching data from 2 GraphQL endpoints. My problem: How can I fetch data from multiple GraphQL endpoints with ApolloClient? Below is my code for my first endpoint:...
What you are trying to accomplish is kinda against Apollo's "One Graph" approach. Take a look at gateways and federation - https://www.apollographql.com/docs/federation/ With that being said, some hacky solution is possible but you will need to maintain a more complex structure and specify the endpoint in every query, ...
Apollo
69,629,051
22
I am working on a react app with react-apollo calling data through graphql when I check in browser network tab response it shows all elements of the array different but what I get or console.log() in my app then all elements of array same as the first element. I don't know how to fix please help
The reason this happens is because the items in your array get "normalized" to the same values in the Apollo cache. AKA, they look the same to Apollo. This usually happens because they share the same Symbol(id). If you print out your Apollo response object, you'll notice that each of the objects have Symbol(id) which i...
Apollo
48,840,223
21
Im trying to figure out how to use apollo-link-http with apollo-upload-client. Both create a terminating link, but how could I use those 2 together? In my index.js I have like this, but it wont work because both links are terminating => const uploadLink = createUploadLink({ uri: process.env.REACT_APP_GRAPHQL_URL }); c...
You do not need the http link if you use apollo-upload-client with version higher than 6. You can try like this: const uploadLink = createUploadLink({ uri: process.env.REACT_APP_GRAPHQL_URL }); const client = new ApolloClient({ link: ApolloLink.from([ authLink, logoutLink, stateLink, uploadLink ]), cache, }); ...
Apollo
49,507,035
21
I'm trying to reset the store after logout in my react-apollo application. So I've created a method called "logout" which is called when I click on a button (and passed by the 'onDisconnect' props). To do that I've tried to follow this example : https://www.apollographql.com/docs/react/recipes/authentication.html But ...
If you need to clear your cache and don't want to fetch all active queries you can use: client.cache.reset() client being your Apollo client. Keep in mind that this will NOT trigger the onResetStore event.
Apollo
48,887,480
20
I am using apollo-server and apollo-graphql-tools and I have following schema type TotalVehicleResponse { totalCars: Int totalTrucks: Int } type RootQuery { getTotalVehicals(color: String): TotalVehicleResponse } schema { query: RootQuery } and Resolver functions are like this { RootQuery: { getTotalVe...
args refer strictly to the arguments provided in the query to that field. If you want values to be made available to child resolvers, you can simply return them from the parent resolver, however, this isn't a good solution since it introduces coupling between types. const resolvers = { RootQuery: { getTotalVehicl...
Apollo
48,382,897
19
I am using <Mutation /> component which has Render Prop API & trying to do Optimistic Response in the UI. So far I have this chunk in an _onSubmit function - createApp({ variables: { id: uuid(), name, link }, optimisticResponse: { __typename: "Mutation", createApp: { __typename: "App...
Apparently this was a bug in Apollo or React Apollo package. Don't know which bug or was it just for React Native but I just updated my dependencies & solved it without changing any code You can check out the full code at https://github.com/deadcoder0904/react-native-darkmode-list
Apollo
50,603,994
19
Hy I am working in a project with Apollo GraphQL method and its working fine. But now the client required for adding additional header with Apollo API's. But after adding the header the API's response return as unAuthorized. I am adding the header as, let apolloAuth: ApolloClient = { let configuration = URL...
UPDATE: Solution for "Apollo Client v0.41.0" and "Swift 5" I had the same issue with Apollo Client v0.41.0 and Swift 5.0 but none of the above solutions worked. Finally able to find a solution after the hours of try-out. The below solution is tested with Apollo Client v0.41.0 And Swift 5 import Foundation import Apollo...
Apollo
55,395,589
19
I have made a bunch of React component calling GraphQL using the Query component and everything is working fine. In one component I need to have some initial data from the database, but without any visual representation. I have tried to use the query component but it seems to be triggered only on the render cycle. I ha...
You could separate the creation of the ApolloClient to a separate file and use an init function to access the client outside of React components. import React from 'react'; import { ApolloClient, HttpLink, InMemoryCache, } from "@apollo/client"; let apolloClient; const httpLink = new HttpLink({ uri: "http://l...
Apollo
56,340,948
18
I have been reviewing the Apollo documentation but I do not see information of how to go about handling server errors in the Apollo client. For example, suppose that the server either: Times out Becomes unreachable Unexpectedly fails How should this be handled in the client? Apollo currently fails with error...
Errors are passed along in the error field on your component props: http://dev.apollodata.com/react/api-queries.html#graphql-query-data-error function MyComponent({ data }) { if (data.error) { return <div>Error!</div>; } else { // ... } } export default graphql(gql`query { ... }`)(MyComponent); That mes...
Apollo
43,646,789
17
I would like to save some Slack messages to a GraphQL backend. I can use the Slack API and what they call "Slack App Commands" so everytime a message is send to my Slack channel, Slack will automatically send a HTTP POST request to my server with the new message as data. I was thinking using an AWS lambda function to f...
GraphQL mutations are simply HTTP POST requests to a GraphQL endpoint. You can easily send one using any HTTP library such as request or axios. For example, this mutation, mutation ($id: Int!) { upvotePost(postId: $id) { id } } and query variable, $id = 1 is an HTTP POST request with a JSON payload of { "q...
Apollo
45,920,986
17
We are currently moving from Relay to React Apollo 2.1 and something I'm doing seems fishy. Context: Some components must only be rendered if the user is authenticated (via an API key), so there is an Authenticator component guarding the rest of the tree. In App.js, it gets used like this (obviously all snippets below ...
Right or wrong, Apollo makes some assumptions about how queries and mutations are used. By convention queries only fetch data while mutations, well, mutate data. Apollo takes that paradigm one step further and assumes that mutations will happen in response to some sort of action. So, like you observed, Query fetches th...
Apollo
49,456,738
17
I've been working on a project lately, which has node.js + express + typescript + Apollo server stack. And while researching on Apollo client, I've stumbled upon TypeScript section. But nothing like that was for server, which leaves me to freedom of choice in this case. So the question is: are there any best practices ...
I wrote a small library and a CLI for this. It generates TypeScript typings for both server (according to your schema) and client (according to your schema and GraphQL documents). It also generates resolvers signature and very customizable. You can try it here: https://github.com/dotansimha/graphql-code-generator The ...
Apollo
50,905,873
17
const httpLink = createHttpLink({ uri: 'http://localhost:3090/' }) const client = new ApolloClient({ link: httpLink, cache: new InMemoryCache() }) client.query({ query: gql` query users { email } `, }) .then(data => console.log(data)) .catch(error => console.error(error)); This query ...
The graphql endpoint you are posting your queries to is missing the /graphql. So your server probably returns an html document containing the 404 error message that starts with < from <html.... Apollo tries to parse that as the query result and fails to do so. Check that httpLink is actually localhost:3090/graphql. Als...
Apollo
53,209,623
17
I have written a GraphQL query which like the one below: { posts { author { comments } comments } } I want to know how can I get the details about the requested child fields inside the posts resolver. I want to do it to avoid nested calls of resolvers. I am using ApolloServer's DataSource API. I ...
You'll need to parse the info object that's passed to the resolver as its fourth parameter. This is the type for the object: type GraphQLResolveInfo = { fieldName: string, fieldNodes: Array<Field>, returnType: GraphQLOutputType, parentType: GraphQLCompositeType, schema: GraphQLSchema, fragments: { [fragment...
Apollo
54,984,035
17
I'm querying for 2 objects which are both needed in the same component. The problem is that one of the queries have to wait on the other and use its id field as an argument for the other. Not sure how to implement this. const PlayerQuery = gql`query PlayerQuery($trackId: Int!, $duration: Int!, $language: String!) { s...
That's a great question because it illustrates a significant difference between REST/RPC style APIs and GraphQL. In REST style APIs the objects that you return only contain metadata about how to fetch more data, and the API consumer is expected to know how to run the JOINs over those tables. In your example, you have a...
Apollo
45,242,250
16
I'am new to GraphQL but I really like it. Now that I'am playing with interfaces and unions, I'am facing a problem with mutations. Suppose that I have this schema : interface FoodType { id: String type: String composition: [Ingredient] } type Pizza implements FoodType { id: String type: String ...
There's a handful of things you could do. For example, if you were to declare your schema programatically, you can get away with something like this: const getPizzaFields = (isInput = false) => { const fields = { type: { type: GraphQLString } pizzaType: { type: GraphQLString } toppings: { type: new GraphQ...
Apollo
48,277,651
16
In my component, I have this code: componentDidMount () { // Setup subscription listener const { client, match: { params: { groupId } } } = this.props client.subscribe({ query: HOMEWORK_IN_GROUP_SUBSCRIPTION, variables: { groupId }, }).subscribe({ next ({ data }) { const cacheData = client.cac...
client.subscribe({ ... }).subscribe({ ... }) will return an instance for your subscription, that you can use to unsubscribe. So something like: componentDidMount () { // Setup subscription listener // (...) this.querySubscription = client.subscribe({ // (...) }).subscribe({ // (...) }) } componentWi...
Apollo
51,477,002
16
I am trying to run a graphql Query but it keeps giving me the "TypeError: String cannot represent value:" error. The schema for my query: type User { active: Boolean! email: String! fullname: String! description: String! tags: [String!]! } type Query { getAll...
What's returned inside your resolver should match the shape specified by your schema. If your User schema is type User { active: Boolean! email: String! fullname: String! description: String! tags: [String!]! } then the array of Users you return should look like this: [{ active: true, email: 'kaisinnn@l...
Apollo
58,636,833
16
As we know a react component is re-rendered when it's props or state changes. Now i'm using useQuery from react-apollo package like below: import { gql, useQuery } from '@apollo/client'; const getBookQuery = gql` { books { name } } `; function BookList() { const { loading, error, data} = useQuer...
A good way of figuring out (roughly) what is happening in useQuery is to consider how you'd do it yourself, e.g. const MyComponent = () => { const [data, setData] = useState(null); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); useEffect(async () => { try { s...
Apollo
66,090,104
16
Intended outcome: MockedProvider should mock my createPost mutation. Actual outcome: Error: No more mocked responses for the query: mutation... How to reproduce the issue: I have a very simple repository. I also created a separate branch with example commit which is breaking the apollo mock provider. 1) Mutation defin...
In the official docs its stated we should add addTypename={false} to the <MockedProvider>. And when I looked at the error message I could see that the __typename was added to the query it was looking for. Something like: { Error: Network error: No more mocked responses for the query: query getDog($dogId: ID!) { dog(d...
Apollo
55,904,192
15
I have the following react-apollo-wrapped GraphQL query: user(id: 1) { name friends { id name } } As semantically represented, it fetches the user with ID 1, returns its name, and returns the id and name of all of its friends. I then render this in a component structure like the following: graphql(Parent...
I don't know why you question is downvoted because I think it is a very valid question to ask. One of GraphQL's selling points is "fetch less and more at once". A client can decide very granually what it needs from the backend. Using deeply nested graphlike queries that previously required multiple endpoints can now be...
Apollo
48,067,366
14
I'm completely stuck on an Apollo problem, for which I've opened a GitHub issue and had zero response on. I'm calling an Apollo mutation, using optimisticResponse. The way it's supposed to work, as I understand it, is that update() gets called twice: first with the optimistic data, then again with the actual data comin...
I was doing some digging and I think I found the source of the problem. Unfortunately, I don't have a solution. In short, the problem might be with a network link called OfflineLink that is used by aws-appsync. Explanation aws-appsync has an ApolloLink called OfflineLink that intervenes with the request function. What ...
Apollo
48,942,175
14
The actual HTTP server instance can be killed with server.close(callback), but I'm not sure what will happen with any pending WebSocket operations (mutations or queries being run through WebSockets). Since http.Server doesn't really know anything about the WebSocket operations, it probably ignores them. How to properly...
Assuming based on the year this question was asked that you are asking about ApolloServer v2. Apollo Server instance does provide stop function which as per documentation waits for all the background tasks running. So it will wait for existing queries to complete before terminating the server. The method is available f...
Apollo
60,640,145
14
Context This question is related to my other question, How to handle apollo client errors crashing page render in Nuxt? , but I'll try to keep this isolated since I'd like this question focused only on Nuxt (minus apollo). However, I decided to ask this separate since I'm looking for an entirely different response/solu...
EDIT: I myself think that the problem lies somewhere in the Vue Apollo plugin or Nuxt Apollo module and how errors are handled there. I would think you can handle the error directly at the Apollo module but that is not possible in SSR. You have to keep in mind that you probably need another solution for both CSR as wel...
Apollo
66,030,282
14
This must be user error, but I've got an app with a simple currentUser query that looks at a JWT for an id, looks it up, and returns the appropriate user. I can look at devtools and see that it's in the cache as __ref:User:19 export const CURRENT_USER_QUERY = gql` query{ currentUser { id fullName ...
I was facing issues with .readQuery() last night. I was getting null returned everytime, though the logic was right. I was calling .readQuery() within a component I imported into my React page. What ended up being my issue is that I was not updating the same query I made in the "parent" react page as the one in the com...
Apollo
66,696,029
14
I'm new to Next.js and have some questions about client-side rendering and server-side rendering in Next.js I see there are two ways to fetch data on Next.js. One of them is to use the useQuery hook but that is only callable on the React component function. Does it mean that it only runs when rendering the page from t...
In Next JS: SSR - Server side rendering - getServerSideProps SSG - Static site generated - getStaticPaths & getStaticProps CSR - Client side rendering - everything else It is important to note that SSG functions are run server-side. On the client, you only want to create a single global instance of Apollo Client. Cre...
Apollo
67,163,527
14
Recently Apollo Client released a websocket subscription feature, but so far I've only seen it used by launching a query using subscribeToMore inside the componentWillMount lifecycle hook. Here is an example taken from https://dev-blog.apollodata.com/tutorial-graphql-subscriptions-client-side-40e185e4be76#0a8f const me...
Turns out it is the subscribe method. I found a description here: https://dev-blog.apollodata.com/graphql-subscriptions-in-apollo-client-9a2457f015fb#eeba ApolloClient.subscribe takes a query and variables, and returns an observable. We then call subscribe on the observable, and give it a next function which will call...
Apollo
45,113,394
13
I'm attempting to wait for the result of a stream with my Apollo Server. My resolver looks like this. async currentSubs() { try { const stream = gateway.subscription.search(search => { search.status().is(braintree.Subscription.Status.Active); }); const data = await stream.pipe(new CollectObjects())....
Had this same problem and was a pretty simple solution. My calls were lasting a bit over 30 seconds and the default timeout was returning 503s as well so I increased that. Assuming you're using apollo-engine (this may be true for some other forms of Apollo), you can set your engine configs like so: export function s...
Apollo
48,490,312
13
I am using React Router 4 for routing and Apollo Client for data fetching & caching. I need to implement a PrivateRoute and redirection solution based on the following criteria: The pages a user is permitted to see are based on their user status, which can be fetched from the server, or read from the cache. The user s...
General Approach I would create an HOC to handle this logic for all of your pages. // privateRoute is a function... const privateRoute = ({ // ...that takes optional boolean parameters... requireLoggedIn = false, requireOnboarded = false, requireWaitlisted = false // ...and returns a function that takes a compo...
Apollo
48,692,649
13
I have a <Query /> in my Home.js file Home.js <Query query={GET_TODOS_BY_PRODUCT} variables={{ id: state.get("selectedProduct.id"), completed: true }} > {({ data: { product } }) => { return <Main todos={product.todos} hashtag={product.hashtag} />; }} </Query> In my Main.js file I ha...
From docs: refetchQueries: (mutationResult: FetchResult) => Array<{ query: DocumentNode, variables?: TVariables} | string>, so probably you need to return an array instead of just the object <Mutation key={v4()} mutation={SWITCH_SELECTED_PRODUCT} refetchQueries={() => { console.log("refetchQueries", product....
Apollo
51,695,337
13
I am currently using the vue-apollo package for Apollo client with VueJs stack with django and graphene-python for my GraphQl API. I have a simple setup with vue-apollo below: import Vue from 'vue' import { ApolloClient } from 'apollo-client' import { HttpLink } from 'apollo-link-http' import { InMemoryCache } from 'ap...
400 errors generally mean there's something off with the query itself. In this instance, you've defined (and you're passing in) a variable called $username -- however, your query references it as $name on line 2.
Apollo
52,247,877
13
Schema: type TrackUser { id: ID! @unique createdAt: DateTime! user: User #note there is no `!` } type User { id: ID! @unique name: String! @unique } I want to get Alls TrackUser where User is not null. What would be the query?
This would be a possible query: query c { trackUsers(where: { NOT: [{ user: null }] }) { name } } Here you can see how it looks in the Playground. I added a name to Trackuser in the datamodel in order to be able to create it from that side without a user.
Apollo
54,313,128
13
In tutorial https://www.howtographql.com/vue-apollo/1-getting-started/ there is presented new HttpLink syntax, but in official docs https://www.apollographql.com/docs/link/links/http/ function createHttpLink is applied. None of these two sources describes the differences between these methods.
There is no fundamental difference between the two. If you look at the apollo-link-http package source here, you can see that the exported createHttpLink method returns a new instance of the ApolloLink class initialized with the options you passed to createHttpLink (lines 62-194). At the end of the same file, you can s...
Apollo
56,663,103
13
I'm following a graphql tutorial on youtube (https://www.youtube.com/watch?v=ed8SzALpx1Q at about 3hr 16min) and part of it uses compose from "react-apollo". However, I'm getting an error because the new version of react-apollo does not export this. I read online that I need to replace import { compose } from "react-a...
compose was removed from React Apollo 3.0.0. If you want to use the same HOC pattern, feel free to use the same copy of lodash's flowRight. Install lodash in your client folder npm install lodash and use this to import compose from lodash (use a capital R in flowRight) import {flowRight as compose} from 'lodash'; Re...
Apollo
57,445,294
13
I'm testing some implementations in the GraphQL Playground, in which I want to send a specific cookie, so that I can fetch it in my resolver. I'm using the built in Http Headers pane in the playground: However, when I add headers named either Cookie or cookie, it doesn't show up when I try to console.log it in my reso...
After extensive searching, documentation reading and etc. I figured out how I could make this work. In the GraphQL playground settings (gear icon), located in the upper right corner of the window: I changed the line "request.credentials" to "include" and SAVING the settings in the UI. Read more here. This line is take...
Apollo
68,114,615
13
Is there a global loading flag available anywhere for react-apollo client? I have a “page wrapper” component that i’d like to apply ui effects to after all the child components have received their data. I have set up apollo with redux so have ready access to the store (http://dev.apollodata.com/react/redux.html) I coul...
I've just released a library that solves this for Apollo 2: react-apollo-network-status. The gist is: import React, {Fragment} from 'react'; import ReactDOM from 'react-dom'; import {ApolloClient} from 'apollo-client'; import {createNetworkStatusNotifier} from 'react-apollo-network-status'; import {createHttpLink} from...
Apollo
43,964,957
12
I can't find or I am looking in the wrong place for any documentation on how fragments are matched. When I use the vanilla Apollo client if I turn off the option of addTypename when I use fragments I get a warning heuristic fragment matching going on! and if I add it this goes away but my response contains many __typen...
The reason for this is that ApolloClient, like Relay, uses a global store to cache your data on the client. In order to do this for you, global ids are required. For some reason, global ids are not something people think about, and in fact, it is something people complain about when switching to Relay all the time. Apo...
Apollo
45,509,228
12
If we look at the todos example, imagine that the application had multiple views (a TodoList page and another page). So instead of "todos" directly referring to an array of todo items, at the top level of the state/store/cache it would actually just be a view with some of its own state. Inside that view, we'd define ...
I have the same question. It seems that apollo-link-state expect a function at the top level of the resolver, so it is not possible to created nested structures as it would be in a Redux store. As the introduction post says, though, it is expected that apollo-link-state would manage only roughly 20% of the state, the r...
Apollo
48,064,706
12
Hi everyone I am a bit stuck on a problem with apollo-angular and apollo-link-error. I've tried a few different ways and I can't seem to catch any errors client-side in my angular web app. I posted my attempts below. Any suggestions or an extra set of eyes would be much appreciated. Basically all I am trying to do is w...
You can see apollo-link-error as a middleware so you have to add it to the fetching process in the apollo client. Meaning that you have to create another apollo link which combines both the http and the error link: import { ApolloLink } from 'apollo-link'; import { HttpLink } from 'apollo-link-http'; import { onErr...
Apollo
49,420,667
12
AppSync uses MQTT over WebSockets for its subscription, yet Apollo uses WebSockets. Neither Subscription component or subscribeForMore in Query component works for me when using apollo with AppSync. One AppSync feature that generated a lot of buzz is its emphasis on real-time data. Under the hood, AppSync’s real-ti...
Ok, here is how it worked for me. You'll need to use aws-appsync SDK (https://github.com/awslabs/aws-mobile-appsync-sdk-js) to use Apollo with AppSync. Didn't have to make any other change to make subscription work with AppSync. Configure ApolloProvider and client: // App.js import React from 'react'; impo...
Apollo
52,960,709
12
I have a set of mutations that trigger the local state of certain types of popups. They're generally set up like this: openDialog: (_, variables, { cache }) => { const data = { popups: { ...popups, dialog: { id: 'dialog', __typename: 'Dialog', type: variables.ty...
Solution is to add fields to the query (vs. declaring the top-level object you want to fetch without specifying the fields to fetch). If you have something like: { popups @client { id dialog } } you must declare some fields to fetch inside dialog, for example id: { popups @client { id dialog { ...
Apollo
53,215,803
12
I'm using Apollo GraphQL on my server, and I'm trying to design my GraphQL API. One question I have is whether or not I should prefer nested queries over root queries. Let's examine both in this example where the current user, me, has many invitations. Root queries me { id name } invitations { id messa...
I'd say it really depends on the case. Personally, I treat nested properties as a context: if the API consumer wants to fetch mine notifications, then it's me { notifications { ... } }, not notifications { ... }. If it makes sense to have a top-level key, for example, there's a concept of global notifications (not use...
Apollo
54,026,744
12
My frontend is localhost:3000, and my GraphQL server is localhost:3333. I've used react-apollo to query/mutate in JSX land, but haven't made a query/mutation from Express yet. I'd like to make the query/mutation here in my server.js. server.get('/auth/github/callback', (req, res) => { // send GraphQL mutation to add ...
This is more likely to be what you're looking for: const { createApolloFetch } = require('apollo-fetch'); const fetch = createApolloFetch({ uri: 'https://1jzxrj179.lp.gql.zone/graphql', }); // Example # 01 fetch({ query: '{ posts { title } }', }).then(res => { console.log(res.data); }); // Example # 02...
Apollo
54,559,928
12
I am trying to do a very basic query via React with Apollo. When I do this query in GraphiQL I nicely get my results back but in my app I get an undefined data object. And a error with a message: Network error: Unexpected end of JSON input The query is: query { category(id: 3) { id children { ...
Ok, i found it. First issue was that i used no-cors option on the ApolloClient Which prevents it from ready the data thus sending back a empty data object. Second issue was that I needed to set my CORS headers on my GraphQL server properly, just for development accepting all with a * that solved it for the developmen...
Apollo
54,589,989
12
Testing the useSubscription hook I'm finding a bit difficult, since the method is omitted/not documented on the Apollo docs (at time of writing). Presumably, it should be mocked using the <MockedProvider /> from @apollo/react-testing, much like the mutations are in the examples given in that link. Testing the loading s...
The problem I can see here is that you're declaring the SubscriptionData component inside the Dashboard component so the next time the Dashboard component is re-rendered, the SubscriptionData component will be re-created and you'll see the error message: No more mocked responses for the query: subscription OnLastPower...
Apollo
61,504,500
12
I'm trying to set up a graphcool subscription / websockets as per this tutorial at How To GraphQL but I'm getting the following message: WebSocket connection to 'wss://subscriptions.graph.cool/v1/###' failed: WebSocket is closed before the connection is established. I'm seem to have everything as per the tutorial...
Can you add the timeout parameter to your client configuration like this: const wsClient = new SubscriptionClient('wss://subscriptions.graph.cool/v1/###', { reconnect: true, timeout: 30000, connectionParams: { authToken: localStorage.getItem(GC_AUTH_TOKEN), } }) There's a slight mismatch between the subsc...
Apollo
45,399,751
11
When I call a mutation on my client I get the following warning: writeToStore.js:111 Missing field updateLocale in {} This is my stateLink: const stateLink = withClientState({ cache, resolvers: { Mutation: { updateLocale: (root, { locale }, context) => { context.cache.writeData({ data:...
I was getting the same warning and solved it by returning the data from the mutation method. updateLocale: (root, { locale }, context) => { const data = { language: { __typename: 'Language', locale, } }; context.cache.writeData({ data }); return data; };
Apollo
48,005,732
11
Is there any reason to use IntrospectionFragmentMatcher to determine concrete types of values returned from interface and union fields? I'm talking about apollo-client. I'm using InMemoryCache with addTypename: true, so the type is known the moment the client gets the response. Meanwhile my console is plagued with wa...
The warnings seem to be a bug in apollo. https://github.com/apollographql/apollo-client/issues/3397
Apollo
50,451,732
11
In my usual experience all single page apps I worked on used JWT as authentication mechanism. I came across api that uses httpOnly cookies for this. Since we can't access such cookie via javascript to know if it is present or not, how does one handle this in react app? My initial idea was to track this by setting some ...
httpOnly just means that the value can't be read by JavaScript. So you make an HTTP request to the server and it will return a response with a Set-Cookie header. Then any future requests will automatically include the cookie. (Just make sure that you set withCredentials or the equivalent.)
Apollo
51,442,150
11
I'm trying Apollo and using the following relevant code: const withQuery = graphql(gql` query ApolloQuery { apolloQuery { data } } `); export default withQuery(props => { const { data: { refetch, loading, apolloQuery }, } = props; return ( <p> <Button variant="contained...
I think that you need to specify notifyOnNetworkStatusChange: true in the query options (it's false by default).
Apollo
55,341,558
11
I have a mutation that fires the channel event 'countIncr', but I don't see the active corresponding subscription fire with the event payload. UPDATE: I've made several updates to this posting and now I'm changing the title to be more representative of where I am. I'm getting a graphqlPlayground error "Subscription fie...
I solved this issue in 2 places ApolloServer.installSubscriptionHandler() TEMPORARILY replacing middleware.apolloSubscriptions() . I configure the subscriptions middleware following this guide: https://www.apollographql.com/docs/graphql-subscriptions/express so I'm going to guess there's something messed up w/ the ver...
Apollo
56,083,422
11
I use the useQuery Hook like this: function Foo() { const { data, error, loading } = useQuery(MY_QUERY, { pollInterval: 1000 }); return ( <> <Bar/> <Baz/> {data} </> ); } Now, both Bar and Baz use the same query. Baz is a sidebar and I'd like to disable the polling while it is active....
You can start and stop polling dynamically with the startPolling and stopPolling functions that are returned by the useQuery hook. For more information, you can see the docs here.
Apollo
58,673,815
11
I have loop - forEach - which find productId for every element of array. I want to fetch my database by productId using apollo query. How to do it? products.forEach(({ productId, quantity }) => // fetch by 'productId' );
From the rules of hooks: Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function. By following this rule, you ensure that Hooks are called in the same order each time a component renders. Hooks cannot be used inside a loop, so you can't use the...
Apollo
60,830,193
11
I am struggling to understand the added value of Express (or Koa, Hapi, etc) integration with Apollo GraphQL server. I see it can work in stand alone mode very well (an example: https://medium.com/codingthesmartway-com-blog/apollo-server-2-introduction-efc4026f5654). In which case should we use it with (or without) in...
If all you need is a GraphQL endpoint, then using the standalone library (apollo-server) is generally preferred because there will be less boilerplate to write (features like subscriptions, file uploads, etc. just work without additional configuration). However, many applications require additional functionality beyond...
Apollo
61,615,755
11
I'm working on testing an Apollo Server RESTDataSource using Jest. My app is written in TypeScript. My class, CDCDataSource extends the abstract class RESTDataSource which itself extends the abstract class DataSource. RESTDataSource has the method get which allows you to pull data from an external REST data source. ...
You are trying to access a protected method. If you don't want to or can't rearchitect your class, you can use ts-ignore to suppress the error. // @ts-ignore` let spy = jest.spyOn(dataSource, 'get').mockImplementation(() => 'Hello'); Or you can extend the original class, with a class made only for testing, th...
Apollo
62,026,238
11
I have a page that consists of 2 components and each of them has its own request for data for example <MovieInfo movieId={queryParamsId}/> const GET_MOVIE_INFO = `gql query($id: String!){ movie(id: $id){ name description } }` Next component <MovieActors movieId={queryParamsId}/> const GET_MOVIE_ACTORS ...
Here is the same solution mentioned by Thomas but a bit shorter const cache = new InMemoryCache({ typePolicies: { Query: { fields: { YOUR_FIELD: { // shorthand merge: true, }, }, }, }, }); This is same as the following const cache = new InMemoryCache({ ty...
Apollo
63,123,558
11
I have a need to create a server farm that can handle 5+ million connections, 5+ million topics (one per client), process 300k messages/sec. I tried to see what various message brokers were capable so I am currently using two RHEL EC2 instances (r3.4xlarge) to make lots of available resources. So you do not need to lo...
ANSWER: While doing this I realized that I had a misspelling in my client setting within /etc/sysctl.conf file for: net.ipv4.ip_local_port_range I am now able to connect 956,591 MQTT clients to my Apollo server in 188sec. More info: Trying to isolate if this is an O/S connection limitation or a Broker, I decided to w...
Apollo
29,358,313
10
I'm using the Apollo Stack with graphql-server-express and apollo-client. Because my backend is not perfect errors can appear and therefore I have to respond to a request with an error for that path. Till now my main problem was authentication and therefore I responded with an error. return new Error(`${data.status}: $...
You could manually look for result.error in the then part of your promise and avoid the use of catch. Also I think you could also add a then after the catch call to handle this specific case. In addition to that, you can also use formatError in your GraphQL server to manually filter and format error messages. The body ...
Apollo
41,852,880
10
Can I fetch more than one element in a GraphQL query? I have many products list data and I want to fetch, for example, three products in my component. I have an array of needed product IDs, can I pass it to query? This is my query for one product: query ProductInCartQuery($id: ID!){ Product(id: $id) { id name ...
It's common and very useful to offer two kind of queries for every type you have: a query to fetch a single node with an id or other unique fields, that's in your case Product (you already have this). a query to fetch many nodes depending on different filter conditions, let's call it allProducts. Then you have two op...
Apollo
44,435,510
10
I'm using react-apollo to build a client that consumes a GraphQL API, however, I'm very stuck on testing. What I want is to mock the server so I can easily test the application without needing to make network calls. I've found some pointers on how to mock the server: https://dev-blog.apollodata.com/mocking-your-server...
I found 2 different ways of creating mocked data for apollo-client queries: The first is to use graphql-tools to create a mocked server based on your backend schema, in order to connect this mocked server with your tests it's possible to create a mockNetworkInterface like this: const { mockServer } = require("graphql-t...
Apollo
45,700,550
10
Background We are working on a fairly large Apollo project. A very simplified version of our api looks like this: type Operation { foo: String activity: Activity } type Activity { bar: String # Lots of fields here ... } We've realised splitting Operation and Activity does no benefit and adds complexit...
GraphQL schema directives can be customized. So below is a solution that prints a warning on the server (Edit 2023: And here's a plugin that propagates the warning to the client): import { SchemaDirectiveVisitor } from "graphql-tools" import { defaultFieldResolver } from "graphql" import { ApolloServer } from "apollo-s...
Apollo
47,056,844
10
I have a App component that I am wrapping into a apollo provider: import React, { Component } from "react"; import { observer, Provider } from "mobx-react"; import { BrowserRouter as Router } from "react-router-dom"; import styled from "styled-components"; import { ThemeProvider } from "styled-components"; // graphQL ...
This seems like a known issue - see here. Try installing graphql-tag and importing gql from this library.
Apollo
47,367,601
10
I have this code: https://codesandbox.io/s/507w9qxrrl I don't understand: 1) How to re-render() Menu component after: this.props.client.query({ query: CURRENT_USER_QUERY, fetchPolicy: "network-only" }); If I login() I expect my Menu component to re-render() itself. But nothing. Only if I click on the Home link it ...
First, let me answer your second question: You can skip an operation using the skip query option. export default graphql(CURRENT_USER_QUERY, { skip: () => !localStorage.get("auth_token"), })(Menu); The problem now is how to re-render this component when the local storage changes. Usually react does not listen on the...
Apollo
47,655,399
10
I'm using Apollo Client and React and I'm looking for a strategy to keep my component and component data requirements colocated in such a way that it can be accessible to parent/sibling/child components that might need it for queries and mutations. I want to be able to easily update the data requirements which in turn ...
Structuring Queries How to structure your code is always a matter of a personal taste but I think the collocation of queries and components is a big strength of GraphQL. For queries I took a lot of inspiration from Relay Modern and the solution looks very close to what you described in the code. Right now as the projec...
Apollo
48,017,187
10
Let's imagine I have a createPost mutation that inserts a new post. In a typical app, that mutation can either: Succeed, returning a Post. Fail, throwing an error (I use apollo-errors to handle this). What I'd like to implement is a middle scenario, where the mutation succeeds (returning a Post); but also somehow re...
All my mutations return a wrapping payload type rather than a single value type (e.g. Post in your case), I also don't ever throw in GraphQL unless it's a real system error -- if it's the consequence of user input or is an otherwise expected case, I model it into the return type. Returning a wrapping payload is general...
Apollo
49,868,843
10
Reaching to you all as I am in the learning process and integration of Apollo and graphQL into one of my projects. So far it goes ok but now I am trying to have some mutations and I am struggling with the Input type and Query type. I feel like it's way more complicated than it should be and therefore I am looking for a...
From the spec: Fields may accept arguments to configure their behavior. These inputs are often scalars or enums, but they sometimes need to represent more complex values. A GraphQL Input Object defines a set of input fields; the input fields are either scalars, enums, or other input objects. This allows arguments to a...
Apollo
52,744,900
10
In a react login component, I'd like to refetch and update the navbar component once login is successful. const loginUser = () => { props.mutate({ variables: { input: { email, password }, }, refetchQueries: [{ query: GET_ME }], }); }; I can see the login and re-fetch in network tab,...
Try adding options: { awaitRefetchQueries: true }, to your props.mutate next to refetchQueries and variables. Queries refetched using options.refetchQueries are handled asynchronously, which means by default they are not necessarily completed before the mutation has completed. Setting options.awaitRefetchQueri...
Apollo
53,474,637
10
Getting this error from Apollo: core.js:14576 ERROR Error: Network error: Error writing result to store for query: {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"AdditionalServices"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kin...
According to that error, you need to add an id field (or _id field, whichever exists) to the selection set for the vendor field. Sounds like you already have another query that returns objects of the type Restaurant, that query included the id and was normalized properly. Apollo won't be able to combine the individual ...
Apollo
55,008,651
10
I am using Strapi with Nuxt.js to implement my first Headless CMS. I am using Apollo and GraphQL. I am running into the current error and I've had no luck to figure this out for days. If I write: query Page($id: ID!) { page(id: $id) { id slug title } } And pass the following variable: { "id" : "1" } ...
To query one item using something other than the primary key (and using just the default built-in queries from Strapi), you need to use the filters avaiable as a where clause: query Pages($slug: String!) { pages(where: {slug: $slug}) { id slug title } } Notice I'm using the endpoint Pages instead of P...
Apollo
59,738,496
10
I'm making unit tests for React components using apollo hooks (useQuery, useMutation), and in the tests I mock the actual queries with apollo's MockedProvider. The problem is that sometimes, my mock doesn't match the query actually made by the component (either a typo when creating the mock, or the component evolves an...
I have submitted a Github issue to the apollo team, in order to suggest a built-in way to do this. Meanwhile, this is my homemade solution. The idea is to give the MockedProvider a custom apollo link. By default, it uses MockLink initialized with the given mocks. Instead of this, I make a custom link, which is a chain ...
Apollo
60,100,062
10
I'm trying to test a data source in my Apollo Server that based on Apollo Server's RESTDataSource (https://www.apollographql.com/docs/apollo-server/data/data-sources/#rest-data-source). I'm trying to test it using Jest. The class has methods that pull in data from an external REST API, as well as from another module ...
Unit testing You can unit test your data source by mocking the RESTDataSource in apollo-datasource-rest as suggested in apollo-datasource-rest + Typescript + Jest in the Apollo Spectrum chat. For this data source: import { RESTDataSource } from 'apollo-datasource-rest' export class MyRestDataSource extends RESTDataSou...
Apollo
62,022,436
10
I am developing a React form that's tied to a GraphQL mutation using the useMutation of Apollo Client. On the server, I perform some validation and in case of errors, I reject the mutation. On the client-side, I use the error object to receive the validation errors. My hook looks like this: const [addDrone, { error }] ...
UPDATE 12/22/2021: As of version 3.5.0 of @apollo/client the useMutation hook now provides a reset method. You can use this method to reset the hook back to its initial state. E.g.: const [addDrone, { error, reset }] = useMutation(ADD_DRONE) Below are some notes from the official documentation on this method. Call re...
Apollo
65,457,513
10
Is it possible to configure the Apollo Client to fetch a single cached Item from a query that returns a list of Items, in order to prefetch data when querying for a single Item? Schema: type Item { id: ID! name: String! } type Query { items: [Item!]! itemById(id: ID!): Item! } Query1: query HomepageList { i...
This functionality exists, but it's hard to find if you don't know what you're looking for. In Apollo Client v2 you're looking for cache redirect functionality, in Apollo Client v3 this is replaced by type policies / field read policies (v3 docs). Apollo doesn't 'know' your GraphQL schema and that makes it easy to set ...
Apollo
65,842,596
10
Some background: I've got a component that immediately calls a useQuery hook upon loading. While that query is running, I spin a loading spinner. Once it completes I render stuff based on the data. I've added a useEffect hook that watches the result of the query and logs the data, which is how I observed this issue. ...
I mocked the result using the result field. the result field can be a function that returns a mocked response after performing arbitrary logic It works fine for me. MyComponent.test.tsx: import { gql, useQuery } from '@apollo/client'; import { useEffect } from 'react'; export const INITIAL_DATA_QUERY = gql` query ...
Apollo
68,732,957
10