vuejs / apollo Goto Github PK
View Code? Open in Web Editor NEW๐ Apollo/GraphQL integration for VueJS
Home Page: http://apollo.vuejs.org
License: MIT License
๐ Apollo/GraphQL integration for VueJS
Home Page: http://apollo.vuejs.org
License: MIT License
If I define a query below:
apollo: {
getTickets: {
query() {
return ticketQuery
} ,
variables() {
return {
offset: this.filters.offset,
limit: this.filters.limit,
}
},
loadingKey: 'loading',
update(data) {
return data.show.rows;
},
result(data) {
}
}
}
I know getTickets
will query automatically when vue components mounted.
But if I want to query manually, how to do?
Example, I click a button and then I want to resend this request.
I'm trying to create a hello world sample app for how to use Vue2 with Scaphol.io GraphQL service using your lib here
I'm not sure how to read your docs, which GraphQL queries to add to the apollo
Component property Object.
Please have a look at:
Mutations can be used standalone without being wrapped in apollo
"container" ?
Subscriptions:
I guess the subscription logic has to go in apollo.subscriptions
and be referenced via this.$apollo
?
I am trying to force a cache invalidation and the fetchPolicy appears not to be working.
await this.$apollo.query({
fetchPolicy: 'network-only',
query: this.query,
variables: {
id: this.id,
},
});
Vue, vue-apollo, apollo-client et al are new technologies for me, so excuse the newbie question :-)
I'm trying to implement a simple error callback for my vue component (vue-loader) to set a variable in my data context, as follows:
apollo: {
requestMappings: {
query: requestMappings,
update(data) {
return data.spring.requestMappings;
},
error: (err) => {
console.log(this)
showNetworkError = true
}
}
}
Here, showNetworkError is not accessible, as the "this" object is the apollo query object. I've tried different styles of "error: function(err) { .. } and "error(err) { ... }", with not much luck. Clearly I feel like I've missed something obvious - how are we able to set data from the callbacks?
Kind regards
James
In a test app I'm setting up to have SSR I get an error that the markup that is served (from the server) is different from the one generated on the client. (because on the client the loading property is true even if instantiated with false in the data
method)
That message goes away when setting the loadingKey property to true
, but then apollo doesn't call the graphql endpoint anymore. Any reason why that is?
To reproduce, change 0
to 1
or true
in here https://github.com/Akryum/frontpage-vue-app/blob/master/src/PostList.vue#L48.
Hi @Akryum
thanks for this great package. I'm using it for a while and it worked great so far. Now with the recent changes in for 2.1.x I'm wondering about the best practice if I run it with Nuxt
and SSR // server-client hydrations.
Do you have any recommended guidelines for it?
Thanks
Hey there. Following the instructions for subscriptions here (https://github.com/Akryum/vue-apollo#subscriptions), I'm getting an error:
Uncaught TypeError: _subscriptionsTransportWs.Client is not a constructor
apollo.js?af01:29
Looking at the API for subscriptions-transport-ws, it looks like maybe the Client
constructor you're referencing here import { Client } from 'subscriptions-transport-ws'
has been renamed to subscriptionClient
?
If having the same name property in nested structure, the result data map messy.
Example:
const showQuery = gql`
query ($offset: Int!, $limit: Int!) {
show(offset: $offset, limit: $limit) {
rows {
id
city { id, name }
star { id, name }
},
count
}
}`;
export default {
apollo: {
tickets: {
query() {
return showQuery;
} ,
variables() {
return {
offset: 0,
limit: 100,
}
},
update(data) {
console.log(data.show.rows);
return data.show.rows;
}
},
}
But the real data is:
{
{
"id": 1,
"city": {
"id": 1,
"name": "ๅนฟๅท",
"__typename": "City"
},
"star": {
"id": 2,
"name": "ๅผ ๅญฆๅ",
"__typename": "Star"
},
"__typename": "Show"
},
{
"id": 19,
"city": {
"id": 3,
"name": "ไธๆตท",
"__typename": "City"
},
"star": {
"id": 3,
"name": "่ฐญๅ้บ",
"__typename": "Star"
},
"__typename": "Show"
}
}
If I change the code to:
const showQuery = gql`
query ($offset: Int!, $limit: Int!) {
show(offset: $offset, limit: $limit) {
rows {
id
city { cityId: id, cityName: name }
star { starId: id, cityName: name }
},
count
}
}`;
The result is correct!!
I found a problem, if request more than one queries, the result hook call multiple times and the response data is messy.
my code:
const categoryQuery = gql`
query {
category {
rows {
id name icon zindex
},
count
}
}`;
const cityQuery = gql`
query {
city {
rows {
id name
},
count
}
}`;
apollo: {
getCategories: {
query() {
return categoryQuery;
} ,
update(data) {
return data.category.rows;
},
result(data) {
console.log('****should print categories****')
console.log(data.category.rows);
},
error(error) {
this.$notify({
title: '้่ฏฏ',
message: '่ทๅๆผๅบ็ฑปๅๅ่กจๅคฑ่ดฅ',
type: 'error'
});
}
},
getCities: {
query() {
return cityQuery;
} ,
update(data) {
return data.city.rows;
},
result(data) {
console.log('---should print cities---')
console.log(data.city.rows);
},
error(error) {
this.$notify({
title: '้่ฏฏ',
message: '่ทๅๅๅธๅ่กจๅคฑ่ดฅ',
type: 'error'
});
}
}
}
But I get the result:
---should print cities--- // correct
["cityA", "cityB", "cityC"]
****should print categories**** // correct
["categoryA", "categoryB", "categoryC", "categoryD"]
---should print cities--- // messy
["categoryA", "categoryB", "categoryC"]
More queries, the data result is more messy.
First, apologies if I'm making a silly newbie mistake. I'm new to Vue and fairly new to Apollo.
I'm writing a simple event-management app. See it here.
I have a Vue component set up as follows:
<template>
<div class="container-fluid">
<h1>{{ title }}</h1>
</div>
</template>
<script>
import gql from "graphql-tag"
export default {
data: () => ({
title: ""
}),
apollo: {
title: {
query: gql`{
event {
title
}
}`
}
}
}
</script>
When I run the component, I get the following error in my console:
Missing title attribute on result
That is indeed accurate. The result object looks like:
{event: {title: "New event"} }
So the value is on the event
key, not on the result. Am I forming my query incorrectly?
Additionally, if I do:
<template>
<div class="container-fluid">
<h1>{{ title }}</h1>
</div>
</template>
<script>
import gql from "graphql-tag"
export default {
data: () => ({
title: ""
}),
apollo: {
title: gql`{
event {
title
}
}`
}
}
</script>
I.e. make title
a simple query, I get:
TypeError: doc is undefined
http://localhost:3000/packages/modules.js?hash=b805b1861f915e66cc02f12e1057e45f06be75f2
Line 13429
Which appears to be buried somewhere in apollo-client
. Indeed, I have to call:
apolloClient.query({query: gql`...`})
to run my query. Were simple queries as documented in the README accidentally broken, are they no longer supported, or am I doing something else incorrectly? Apologies for lumping lots into one question, but this isn't working as documented for me and I don't quite know why.
Thanks.
I have adapted the example in my setup dev server runs fine but production build has the following error. please let me know if you need more information??
Great work btw!
`Hash: 309b2fe3f5f6a95a4d0c
Version: webpack 2.1.0-beta.20
Time: 4002ms
Asset Size Chunks Chunk Names
client.efaf137e.js 49.9 kB 0 [emitted] client
vendor.699ece51.js 852 kB 1 [emitted] vendor
styles.1c7b9d16.css 724 bytes 0 [emitted] client
styles.1c7b9d16.css.map 96 bytes 0 [emitted] client
vendor.699ece51.js.map 1.06 MB 1 [emitted] vendor
index.html 383 bytes [emitted]
[88] multi vendor 64 bytes {1} [built]
+ 92 hidden modules
ERROR in vendor.699ece51.js from UglifyJs
SyntaxError: Unexpected token: name (apolloClient) [vendor.699ece51.js:30261,4]`
WARNING: npm peer requirements (for apollo) not installed:
Read more about installing npm peer dependencies:
http://guide.meteor.com/using-packages.html#peer-npm-dependencies
Hey, I have some weird things happening. If I am using keep-alive on router apollo is doing cached requests from other routes.
Example:
If I open user route it's okay, but if I open other route from user route, apollo does the user route query again.
In the readme it says we should import Apollo client like so:
import ApolloClient, { createNetworkInterface, addTypename } from './apollo-client';
But it is only working after removing the curent directory prefix:
import ApolloClient, { createNetworkInterface, addTypename } from 'apollo-client';
Update to final API.
Hi!
First of all, thank you for this project! It's helped me make an amazingly smooth transition to Vue from React.
My question is: Is there a skip method we can use to skip queries like shown here:
http://dev.apollodata.com/react/queries.html#graphql-skip
It would be great if we could skip based on a provided function. Here's what I'm thinking:
export default {
...
apollo: {
user: {
query: FETCH_CURRENT_USER,
skip() {
return !isAuthenticated
},
...
}
}
}
If the skip uses a reactive data source in it's return, then it would automatically trigger the query if that component is already mounted.
Is this something that would be of interest to add to vue-apollo
? Can you think of any other ways this can easily be achieved?
I look forward to hearing from you.
apollo:{ oncehello: {query:gql
{oncehello:hello{content}}, fetchPolicy: 'cache-only', result(data){ console.log(data) }} }
When i use the 'cache-only' to query, it can call result() twice ? But ohters are not wrong.
In my opinion, the query should that read the data from the cache once, and call result once.
version: [email protected]
I'm following this guide: https://blog.meteor.com/create-a-simple-hello-world-app-with-meteor-and-apollo-64bab66a456f#.lre40nei5
Need to install graphql tools now.
import { makeExecutableSchema } from 'graphql-tools';
I successfuly fetched an array from server, it stores in vue data. But when I'm trying to modify it, I getting an error:
vuedraggable.js?bcd0:177 Uncaught TypeError: Cannot add/remove sealed array elements
What should I do by design of apollo? Clone this array in mutable one?
Beta 9 has error with the plugin registry with an error saying
prepare not defined
[email protected] requires a peer of apollo-client@^0.5.0 but none was installed.
The last 0.5 is 2 month old. npm wouldn't install it itself even if you told it to as per instructions (or at least meet the dependency).
Create recipes on par with React documentation.
We have a consistent set of hello world apps going for other UI tech:
https://github.com/apollostack/frontpage-react-app
https://github.com/apollostack/frontpage-angular2-app
https://github.com/apollostack/frontpage-react-native-app
It would be informative to see an app with the same features, against the same server, but with Vue.
Hey, i have some updateQueries to update apollo cache but doesnt work.
Maybe this is related to apollographql/apollo-client#1129 ?
Code:
updateQueries: {
animal: (previousQueryResult, { mutationResult }) => {
return {
animal: {
...previousQueryResult.animal,
records: [mutationResult.data.createRecord, ...previousQueryResult.animal.records],
}
}
}
},
apollo: {
chapters: {
query: buildDocument(GET_CHAPTERS),
variables () {
return {
publisher: 'x',
semester: 'y'
}
},
skip () {
console.log(!this.chapter)
return !!this.chapter
}
}
}
I can't see skip log this status, vue-apollo version is 1.3.0
Hey, after setuping websocket i get this error,
anybody know what i need to change?
Uncaught ReferenceError: WebSocketFrame is not defined
My connection code:
import ApolloClient, { createNetworkInterface, addTypename } from 'apollo-client';
import { Client } from 'subscriptions-transport-ws';
import VueApollo, { addGraphQLSubscriptions } from 'vue-apollo'
const networkInterface = createNetworkInterface({
uri: 'http://localhost/graphql',
transportBatching: true,
});
const wsClient = new Client('ws://localhost:3030');
const networkInterfaceWithSubscriptions = addGraphQLSubscriptions(
networkInterface,
wsClient,
);
const apolloClient = new ApolloClient({
networkInterface: networkInterfaceWithSubscriptions,
});
Vue.use(VueApollo, {
apolloClient,
});
and some missing files
WARNING in ./app/~/websocket/lib/BufferUtil.js
Module not found: Error: Cannot resolve 'file' or 'directory' ../build/Release/bufferutil in C:\laragon\www\vet-desktop\app\node_modules\websocket\lib
@ ./app/~/websocket/lib/BufferUtil.js 9:19-57
WARNING in ./app/~/websocket/lib/BufferUtil.js
Module not found: Error: Cannot resolve 'file' or 'directory' ../build/default/bufferutil in C:\laragon\www\vet-desktop\app\node_modules\websocket\lib
@ ./app/~/websocket/lib/BufferUtil.js 11:19-57
WARNING in ./app/~/websocket/lib/Validation.js
Module not found: Error: Cannot resolve 'file' or 'directory' ../build/Release/validation in C:\laragon\www\vet-desktop\app\node_modules\websocket\lib
@ ./app/~/websocket/lib/Validation.js 9:21-59
WARNING in ./app/~/websocket/lib/Validation.js
Module not found: Error: Cannot resolve 'file' or 'directory' ../build/default/validation in C:\laragon\www\vet-desktop\app\node_modules\websocket\lib
@ ./app/~/websocket/lib/Validation.js 11:21-59
This would allow targeting multiple graphQL endpoints.
Proposed syntax:
// Installation
Vue.use(VueApollo, {
clients: {
cliendId: apolloClientInstance,
},
defaultClient: apolloClientInstance,
})
apollo: {
// Default apollo client for this component
$use: 'clientId',
// Query-specific
myQuery: {
use: 'clientId',
},
},
I'm not sure who's the guilty one :), but here's the thing. I created a fresh vue
application using the vue-cli (vue init webpack {projectname}). Then I installed the vue-router and finally the [vue-apollo] package with [apollo-client].
Everything seams to be working, but when I try to prerender my project using the prerender-spa-plugin I see errors inside compiled files. At first I thought that pre-renderer has problems with async
operations, but it turned out that it works without problems. Only the apollo
part is not working.
This is the error that I see:
TypeError: undefined is not an object (evaluating 'r._updateFromParent')
http://localhost:8000/static/js/vendor.0c3c80024a3bb7c58eec.js:12 in st
http://localhost:8000/static/js/vendor.0c3c80024a3bb7c58eec.js:13 in y
http://localhost:8000/static/js/vendor.0c3c80024a3bb7c58eec.js:13 in v
http://localhost:8000/static/js/vendor.0c3c80024a3bb7c58eec.js:13 in y
http://localhost:8000/static/js/vendor.0c3c80024a3bb7c58eec.js:13
http://localhost:8000/static/js/vendor.0c3c80024a3bb7c58eec.js:12 in _update
http://localhost:8000/static/js/vendor.0c3c80024a3bb7c58eec.js:12
http://localhost:8000/static/js/vendor.0c3c80024a3bb7c58eec.js:13 in get
http://localhost:8000/static/js/vendor.0c3c80024a3bb7c58eec.js:13 in run
http://localhost:8000/static/js/vendor.0c3c80024a3bb7c58eec.js:12 in T
http://localhost:8000/static/js/vendor.0c3c80024a3bb7c58eec.js:13 in t
Here is also a repository with my code. Just run npm run build
, then check the ./dist/index.html
file.
Can / should vue-apollo be used with vuex?
If yes then could you please show examples?
There is no mention about it in the Readme section about mutations.
I needed to control the loading state to avoid "overloading" and found out that the documentation was not correctly refering to the option watchLoading
(it seemed to be called loadingchangecb
). I found the naming in the documentation more appropriate and refactored it as it mentioned in the docs.
Here is my pull request: #44
Is there a way to map multiple objects from a single query? It currently seems to expect one object to equal one query.
Right now it seems that I either need to do multiple queries, like below (my queries are defined as constants elsewhere). This results in two queries or I can turn on batch to do one query but that requires changing our backend to accommodate that batched format (we are not using Apollo Server).
apollo: {
clients: {
query: clientQuery,
loadingKey: 'loading'
}
,
client_statuses: {
query: clientStatusesQuery,
loadingKey: 'loading'
}
}
or I have to use the Apollo Client directly to separate it out, like below.
created() {
this.$apollo.query({
query: clientsAndStatusesQuery
})
.then(result => {
this.clients = result.data.clients
this.client_statuses = result.data.client_statuses
});
},
Another note, in the example it says to use watchQuery. I get "Uncaught TypeError: this.$apollo.watchQuery(...).then is not a function(โฆ)". But just "query" works fine.
Any help would be appreciated! Thank you!
hi,
i'm using the same query in 4 components of my app. this leads to the query being run 4 times when my app loads. i suspect that the following code in SmartQuery
is the reason:
if (this.starting) {
this.options.forceFetch = true
}
so i'm wondering what the purpose of the force fetching is. why is it necessary to set this here?
I get this:
ERROR in .//vue-apollo/index.js/vue-apollo/index.js 1:17-44
Module not found: Error: Can't resolve './lib/vue-plugin' in '/srv/http/frontpage-vue-app/node_modules/vue-apollo'
@ ./
@ ./src/main.js
@ multi main
It worked for me yesterday when i cloned the package, but not today.
Get following error:
http://localhost:3000/graphql 405 (Method Not Allowed)
HTTPFetchNetworkInterface.fetchFromRemoteEndpoint @ VM8112:73
(anonymous) @ VM8112:90
localhost/:1 Fetch API cannot load http://localhost:3000/graphql. Response for preflight has invalid HTTP status code 405
vue-plugin.js?3c73:207 Error sending the query undefined TypeError: Failed to fetch
Using https://atmospherejs.com/meteor/apollo. Any idea for why the OPTION
request needs to be made? Or is that the apollo client that is doing that?
I'm evaluating the amazing Quasar framework with vue-apollo.
Im using the following setup from the readme file in the app.js startup file (Vue being already imported by Quasar):
import ApolloClient, { createNetworkInterface, addTypename } from 'apollo-client';
import VueApollo from 'vue-apollo';
// Create the apollo client
const apolloClient = new ApolloClient({
networkInterface: createNetworkInterface({
uri: 'http://localhost:8080/graphql',
transportBatching: true,
}),
queryTransformer: addTypename,
});
// Install the vue plugin
Vue.use(VueApollo, {
apolloClient,
});
and I get Uncaught ReferenceError: prepare is not defined
, pointing here.
apollo: {
oncehello: {
query:gql{oncehello:hello{content}}
, result(){
console.log(this.$apollo.queries.oncehello); // It is undefined
this.$apollo.queries.oncehello.skip = true;
}
}
}
I try to set skip of the query after watchQuery in the result() , but the object was undefined in queries when the result() was called.
Version: [email protected]
Is there anyway to access Vue's data and props from the Apollo option? In the following example "name" is undefined. $route.params are also inaccessible
export default {
// Local state
data: () => ({
Trainer: { pokemons: [] },
loading: 0,
dialogVisible: false,
newOpen: false,
selected: {},
name: 'Alex'
}),
// Apollo GraphQL
apollo: {
Trainer: {
query: queries.Trainers.get,
variables: {
name: this.name,
page: this.$route.params.page
},
loadingKey: 'loading',
}
}
Vue-apollo mixin registers beforeCreate hook and it's called multiple times with components that are using mixins which results in an error: Cannot redefine property: $apollo
Some other plugins have guards against double initialization: vue-resource/index.js#L13 or vue-router/install.js#L7
Vue.use()
function (in /use.js#L8
) is guarded against double install too.
Maybe some kind of if(this.$apollo) { return; }
before you defineProperty would help?
This is not directly related to vue-apollo
but because I write vue
application I decided to address this issue here.
My Vue application file size (the final build.js
) is around 250KB (the whole application). When I attach vue-apollo
and apollo-client
, the file size exceeds to 350KB. Apollo client equips you with powerful tools but 100KB+
well... I would say this is huge.
What can we do about that?
apollo-client worked in redux , so how to implement a vue component get data from apollo store to share data between with another component. thanks
is it just me or loadingKey is not woking for mutations?
The only difference between query and watchQuery is that watchQuery updates when the client-side cache is updated by a mutation or another query. In react-apollo
, for example, all queries use watchQuery
.
What would be the use case for a "non-reactive" query? I feel like it shouldn't be the default. But up to you, of course.
https://adda-spb.herokuapp.com/graphiql
this is my api with backend rails + graphql but i am getting this error
http://prntscr.com/di6z8v
Hey, can you give an example of how vue-apollo works with fragments? I'm not really clear how that works with this lib.
Hello, I'm trying to get an isomorphic vue
vue-router
vue-apollo
application running and I've run into some issue.
vue-apollo
does not run on the server by default. To try to get around this I first tried to manually run queries before rendering the application on the server by pullinf from router.getMatchedComponents
. This lead me to my next issue.
vue-router
's router.getMatchedComponents
yields only the component definitions, not instances. This means we cannot run the queries in the context of the running state of the application. This lead me to try to run the queries from within component lifecycle hooks.
Unfortunately component lifecycle hooks cannot be asynchronous. As a result the queries are run after the application has already been rendered and sent down the wire.
I'm more or less out of ideas now, and I'll probably just fall back to using apollo client directly with vuex, which is pretty terrible.
It seems like this plugin has no way to operate in conjunction with server side rendering. I'd love to be wrong however. Do you have any ideas how it could be done?
Please one example, the implementation use wacthQuery and fetchMore for create pagination...
ref: http://dev.apollodata.com/react/cache-updates.html#fetchMore
this is my code in ready()
const query = this.$apollo.client.watchQuery({
query: queryList,
variables: { offset: this.offset },
forceFetch: true
})
query.fetchMore({
variables: { offset: this.offset },
updateQuery: (previousResult, { fetchMoreResult }) => {
if (!fetchMoreResult.data) { return previousResult }
return { employees: [ ...previousResult.employees, ...fetchMoreResult.data.employees ] }
}
})
error: QueryManager.js?a470:365Uncaught (in promise) Error: ObservableQuery with this id doesn't exist
I updated to [email protected]
and [email protected]
. All of my queries seem to be working fine but I can't seem to access the client now. Is there a new way to access this.$apollo.client
with the new provider setup?
I am using following middleware to handle authorization:
networkInterface.use([{
applyMiddleware(req, next) {
if (!req.options.headers) {
req.options.headers = {};
}
const accessToken = store.state.session.accessToken;
if (accessToken) {
req.options.headers['authorization'] = `Bearer ${accessToken}`;
}
next();
}
}]);
In my component (for authenticated users) I use following query:
apollo: {
projects: {
query: gql`
query projectList {
projects {
id
name
created_at
}
}
`,
fetchPolicy: 'cache-and-network',
},
},
When user logs out, I clear accessToken, call apollo.resetStore()
and redirect to /login
page.
The problem is that after calling apollo.resetStore()
apollo automatically refetches projectList query, however it receives 401 error since accessToken had been cleared. I tried to use $skipAll
option like this:
apollo: {
projects: {
query: gql`
query projectList {
projects {
id
name
created_at
}
}
`,
fetchPolicy: 'cache-and-network',
},
$skipAll () {
console.log('SKIP', !this.isLoggedIn);
return !this.isLoggedIn;
},
},
But it is not called at all when apollo automatically refetches queries after apollo.resetStore()
. Is there any other way to clearStore without refetching queries?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.