Vue Apollo: How can I query GraphQL using an object as Input argument? - vue.js

I would like to create a checkout object via the GraphQL API provided by the Saleor eCommerce platform.
According to the gql playground there is a mutation to do so that takes a CheckoutCreateInput object as it's argument.
Here is an example mutation that works fine within the playground.
Here is the current code that I have tried (I am doing this within a vuex action)
export const actions = {
addToCart({ commit, dispatch }, cartItem) {
const currentCartItems = this.state.cartItems
// Check to see if we already have a checkout object
if (this.state.checkoutId !== '') {
// Create a new checkout ID
console.log('creating new checkout object')
try {
this.app.apolloProvider.defaultClient
.mutate({
mutation: CREATE_CART_MUTATION,
variables: {
checkoutInput: {
lines: { quantity: 10, variantId: 'UHJvZHVjdFZhcmlhbnQ6NQ==' },
email: 'test#test.com'
}
}
})
.then(({ data }) => {
console.log(data)
})
} catch (e) {
console.log(e)
}
} else {
console.log('checkout id already set')
}
// TODO: Check to see if the cart already contains the current Cart Item
commit('ADD_CART_ITEM', cartItem)
}
and here is the CREATE_CART_MUTATION:
import gql from 'graphql-tag'
export const CREATE_CART_MUTATION = gql`
mutation($checkoutInput: CheckoutCreateInput!) {
checkoutCreate(input: $checkoutInput) {
checkout {
id
created
lastChange
lines {
id
variant {
id
name
}
quantity
totalPrice {
gross {
localized
}
net {
localized
}
}
}
totalPrice {
gross {
localized
}
net {
localized
}
}
}
}
}
`
On the server this comes back with the following error:
graphql.error.base.GraphQLError: Variable "$checkoutInput" got invalid value {"email": "test#test.com", "lines": {"quantity": 10, "variantId": "UHJvZHVjdFZhcmlhbnQ6NQ=="}}.
In field "lines": In element #0: Expected "CheckoutLineInput", found not an object.

Looks like I was most of the way there, I was just passing a single lines object rather than an array of them. The correct code is as follows:
try {
this.app.apolloProvider.defaultClient
.mutate({
mutation: CREATE_CART_MUTATION,
variables: {
checkoutInput: {
lines: [
{ quantity: cartItem.quantity, variantId: cartItem.variantId }
],
email: 'test#test.com'
}
}
})
.then(({ data }) => {
console.log('mutation done!')
commit('SET_CHECKOUT_OBJECT', data.checkoutCreate.checkout)
})
} catch (e) {
console.log('error:')
console.log(e)
}

Related

Why am I not getting updates from my subscription?

I am trying to set up GraphQL Subscriptions but it seems to get connected to the backend but it's not pushing any updates.
On frontend, I am using Nuxt 2 and that's how I am trying to get it working:
That's my test query
export const pendingInquiresSubscription = () => {
return gql`
subscription PendingInquires {
countPendingInquires {
amount
}
}`
}
My smartQuery on the page component
apollo: {
$subscribe: {
pendingInquires: {
query: pendingInquiresSubscription(),
result({ data, loading }) {
this.loading = loading;
console.log(data)
},
error(err) {
this.$notify({ message: `Что-то пошло не так пытаясь обновить количество новый запросов: ${err.message}`, type: 'error' })
},
}
}
},
Backend:
my pubsub
import { RedisPubSub } from 'graphql-redis-subscriptions';
import Redis from 'ioredis';
const REDIS_DOMAIN_NAME = '127.0.0.1'
const PORT_NUMBER = 6379
const options = {
host: REDIS_DOMAIN_NAME,
port: PORT_NUMBER,
retryStrategy: (times: any) => {
return Math.min(times * 50, 2000);
}
}
export const pubsub = new RedisPubSub({
publisher: new Redis(options),
subscriber: new Redis(options)
})
My Schema:
extend type Subscription {
countPendingInquires: PendingInquires!
}
type PendingInquires {
amount: Int!
}
My resolver
...
Subscription: {
countPendingInquires: {
subscribe: () => pubsub.asyncIterator(['countPendingInquires'])
},
},
...
That's the way I am trying to push the event:
pubsub.publish('countPendingInquires', {
PendingInquires: {
amount: await TelegramInguireModel.find({ }).countDocuments()
}
})
And I also wonder if there is any built-in way to set the initial state for subscriptions.
The issue was in the way I was trying to push the event
The correct way of pushing is like this:
pubsub.publish('countPendingInquires', {
countPendingInquires: { // <- here was the issue
amount: await TelegramInquireModel.find({ }).countDocuments()
}
)
I've just set wrong subscription name

Pass data from vue file to js file in vuejs?

In file : Product.vue
beforeCreate() {
const productId = this.$route.params.id;
axios
.get("/localhost/api/product/" + productId)
.then((res) => {
console.log(res.data); // result : {name: 'Iphone', status: 3, quantity: 100, price: 800}
})
.catch((error) => {
console.log(error);
});
},
I have a file productData.js on the same level as Product.vue. Now I want to transfer data of res.data through productData.js, how to do? In other words in productData.js I want to get the result of res.data when I call the API. Thanks.
update :
let data = null;
function initData(apiRes) {
data = apiRes;
console.log(data); // Output: "Hi from server"
// Do something with Data
}
console.log(data) // I want to get data outside the initData function
export { initData };
Simplest way is:
Product.vue
<script>
import { initData } from "./productData.js";
export default {
name: "Product",
props: {
msg: String,
},
data() {
return {
apiRes: "",
};
},
mounted() {
// your api call
this.apiRes = "Hi from server";
initData(this.apiRes);
},
};
</script>
productData.js
let data = null;
function initData(apiRes) {
data = apiRes;
console.log(data); // Output: "Hi from server"
// Do something with Data
doSomethingWithData();
}
function doSomethingWithData() {
// Your app logic that depends on data
// Here data will have value from API
}
// Here data is always null
export { initData };

Vue3: how to pass an object from provide to index

I've been using vue.js for a few weeks and I would like to understand how to globally inject to child components an object coming from the server.
When I try to inject the object using inject:['user'] to a child component it returns an empty object.
data() {
return {
user: []
}
},
methods: {
getLoggedUserData() {
axios.get('/api/get-user/' + window.auth.id
).then(response => {
this.user = response.data.user;
});
}
},
provide: {
return {
user: this.user
}
},
created() {
this.getLoggedUserData();
}
The provide option should be a function in this case to get access to this.user property:
export default {
provide() {
return {
user: this.user
}
}
}
For descendants to observe any changes to the provided user, the parent must only update user by subproperty assignment (e.g., this.user.foo = true) or by Object.assign() (e.g., Object.assign(this.user, newUserObject)):
export default {
methods: {
async getLoggedUserData() {
const { data: user } = await axios.get('https://jsonplaceholder.typicode.com/users/1')
// ❌ Don't do direct assignment, which would overwrite the provided `user` reference that descendants currently have a hold of:
//this.user = user
Object.assign(this.user, user) ✅
}
}
}
demo

Vue-apollo query doesn't render variables

In Nuxt.js, I'm trying to do a query like this with the nuxt apollo-module based in vue-apollo
apollo: {
magazines: {
query: gql`query($id: String!) {
magazines( where: { url_contains:$id })
{
url
title
thumbnail
}
}`,
prefetch: ({ route }) => ({ id: route.params.id }),
variables() {
return {
id: this.$route.params.id
}
}
}
The query is sent, but the variable $id is sent unrendered (in the petition, I can see query($id: String!)—instead of query('my-page-route': String!)— and where: { url_contains:$id } as it is—instead of where: { url_contains:'my-page-route' }
The query is surprisingly valid, as it responds with all the items in the db —so it doesn't apply the where: { url_contains:$id }
I have tried with query($id: String) but that doesn't change anything. Any hints about what could be going wrong?
Thanks in advance!

How to get value from state as my vuex getter is returning empty value in observer

Getter is returning empty value in observer. But the state is setting properly in the mutation.
Not able to check in Vuex dev tools in console as it says "No Store Detected". I've checked it by logging it in console
Vue File :
computed: {
...mapGetters('listings', ['listingContracts']),
},
methods: {
...mapActions('listings', [
'productBasedListings',
]),
},
onChange(product) {
this.productBasedListings( product.id );
console.log('LIST:', this.listingContracts); // Empty in observer
},
Store :
state: {
contracts: [],
},
getters: {
listingContracts(state) {
console.log('GETTER', state.contracts); // Empty in observer
return state.contracts;
},
},
mutations: {
setListing(state, { lists }) {
state.contracts = lists;
console.log('AFTER MUTATION:', state.contracts); // Setting the value properly
},
},
actions: {
async productBasedListings({ commit }, { id, state }) {
let listing = [];
try {
listing = await publicApi.listings(id);
console.log('ACTION:', listing);
commit({
lists: listing,
type: 'setListing',
});
} catch (e) {
console.error(`Failed to change #${id} state to #${state}:\t`, e);
throw e;
}
},
}
Here "Getter" does not have any values but "After Mutation" we have the values.
Because initially the store variable is empty.The values are itself set in the mutation.Hence showing up after mutation is called.
Well now to get data after mutation is fired use async await in your method as below:
async onChange(product) {
await this.productBasedListings( product.id ).then(() => {
console.log('LIST:', this.listingContracts);
})
},