Using GraphQL useQuery Variables - graphql

I'm currently on client side trying to make a query but can't go through. However it works when testing at the back-end.
back-end docs & getting response
front-end code (getting 400 code)
const QUERY_SPECIFIC_CATEGORY_PRODUCTS = gql` query QUERY_SPECIFIC_CATEGORY_PRODUCTS($category: String!) { category(input: { title: $category }) { name } } `; const { data, loading, error } = useQuery(QUERY_SPECIFIC_CATEGORY_PRODUCTS, { // prettier-ignore variables: {input: { title: "clothes" }} });

When you call useQuery just pass the "clothes" value as the category variable:
const { data, loading, error } = useQuery(QUERY_SPECIFIC_CATEGORY_PRODUCTS, {
variables: { category: "clothes" },
});

Related

Apollo GQL useMutation does not return data field

I have the following mutation that works just fine in the Sandbox (it creates and returns the bookmark):
mutation CreateBookmark ($options: BookmarkInput!) {
createBookmark(options: $options) {
bookmark {
id
title
url
}
}
}
When I try to create a bookmark from my react app, the bookmark is being created but data is undefined.
This is my code:
const CREATE_BOOKMARK = gql`
mutation CreateBookmark($options: BookmarkInput!) {
createBookmark(options: $options) {
bookmark {
id
title
url
}
}
}
`;
const [mutateFunction, {data, error, loading}] = useMutation(CREATE_BOOKMARK);
mutateFunction({
variables: {
options: {
title: bookmark.title,
url: bookmark.url,
},
},
});
When I try to console.log(data) it returns undefined.
I have also tried to not destructure the object that is being returned like this:
const [mutateFunction, obj] = useMutation(CREATE_BOOKMARK);
When I console.log(obj), it returns this:
{
error: ...,
loading: ...,
client: ...,
reset: ...
}
As you can see, there is no data field. Why is this happening?

WpGraphQL query returns null

I'm having this GraphQL query from headless Wordpress in Nexjs via WpGraphQl plugin:
export const GET_POSTS_BY_CATEGORY_SLUG = gql`
query GET_POSTS_BY_CATEGORY_SLUG( $slug: String, $uri: String, $perPage: Int, $offset: Int ) {
${HeaderFooter}
page: pageBy(uri: $uri) {
id
title
content
slug
uri
seo {
...SeoFragment
}
}
categories(where: {slug: $slug}) {
edges {
node {
slug
posts: posts(where: { offsetPagination: { size: $perPage, offset: $offset }}) {
edges {
node {
id
title
excerpt
slug
featuredImage {
node {
...ImageFragment
}
}
}
}
pageInfo {
offsetPagination {
total
}
}
}
}
}
}
}
${MenuFragment}
${ImageFragment}
${SeoFragment}
`;
And this is my getStaticProps function:
export async function getStaticProps(context) {
const { data: category_IDD } = await client.query({
query: GET_POSTS_BY_CATEGORY_SLUG,
});
const defaultProps = {
props: {
cat_test: JSON.parse(JSON.stringify([category_IDD])),
},
revalidate: 1,
};
return handleRedirectsAndReturnData(defaultProps, data, errors, "posts");
}
If i pass it like this in props:
const defaultProps = {
props: {
cat_test: category_IDD,
},
i get an error saying:
SerializableError: Error serializing `.cat_test` returned from `getStaticProps` in "/category/[slug]". Reason: `undefined` cannot be serialized as JSON. Please use `null` or omit this value.
But when i JSON.parse as the code above, i get null
Whats wrong with this query?
Just noticed that the $slug is an array of strings, so here should be:
query GET_POSTS_BY_CATEGORY_SLUG( $slug: [String], $uri: String, $perPage: Int, $offset: Int )
instead of $slug: String
You're not actually passing the $slug variable to the query.
For instance if your page route is /category/[slug].js your getStaticProps should look something like this.
export async function getStaticProps(context) {
const { slug } = context.params;
const { data: category_IDD } = await client.query({
query: GET_POSTS_BY_CATEGORY_SLUG,
variables: { slug },
});
const defaultProps = {
props: {
cat_test: JSON.parse(JSON.stringify([category_IDD])),
},
revalidate: 1,
};
return handleRedirectsAndReturnData(defaultProps, data, errors, "posts");
}

Parameterized queries qraphQL

I want to make parameterized requests from the Apollo client to the Apollo server.
On client:
const GET_VALUES = gql`
query Values($desc: String!) {
Values
}
`;
function ValueSelector({ pickValue, dirDesc }) {
const { loading, data, error } = useQuery(GET_VALUES, {
variables: { dirDesc },
});
}
On server (schema):
type Query {
Values(desc: String!): [String]
#cypher(
statement: "MATCH (:Dir{description:$desc})-[:value]->(v) RETURN collect(v.TXTLG)"
)
}
Result:
[GraphQL error]: Message: Field "Values" argument "desc" of type "String!" is required, but it was not provided., Location: [object Object], Path: undefined
[Network error]: ServerError: Response not successful: Received status code 400
You should use desc instead of dirDesc in variables param of useQuery. Try this:
const { loading, data, error } = useQuery(GET_VALUES, {
variables: { desc: dirDesc },
});
const GET_VALUES = gql`
query Values($desc: String!) {
Values(desc: $desc)
}
`;
function ValueSelector({ pickValue, dirDesc }) {
const { loading, data, error } = useQuery(GET_VALUES, {
variables: { desc:dirDesc},
});
Your query declaration on the client is missing the actual variable. It should be something like this
const GET_VALUES = gql`
query Values($desc: String!) {
Values(dirDesc: $desc)
}
`;
Then you can use useQuery passing dirDesc.

Apollo GraphQL: Calling a Query Twice with apolloClient.query?

I have the following query:
const GET_MY_USERINFOFORIMS_QUERY = gql`
query($userID: String!){
myUserDataForIMs(userID:userID){
name_first
name_last
picture_medium
}
} `;
const withUserInfoForIMs = graphql(GET_MY_USERINFOFORIMS_QUERY, {
options({ userID }) {
return {
variables: { userID: `${userID}`}
};
}
,
props({ data: { loading, myUserDataForIMs } }) {
return { loading, myUserDataForIMs };
},
name: 'GET_MY_USERINFOFORIMS_QUERY',
});
From the Apollo docs, it looks like I may be able to call this query twice from inside the component, using apolloClient.query, doing something like this:
client.query({ query: query1 })
client.query({ query: query2 })
Is there a way to call the query twice, passing a different userID each time?
Found it. :)
const localThis = this;
this.props.ApolloClientWithSubscribeEnabled.query({
query: GET_MY_USERINFOFORIMS_QUERY,
variables: {userID: fromID},
}).then((result) => {
localThis.setState({ fromAvatar: result.data.myUserDataForIMs[0].picture_thumbnail });
});
this.props.ApolloClientWithSubscribeEnabled.query({
query: GET_MY_USERINFOFORIMS_QUERY,
variables: {userID: toID},
}).then((result) => {
localThis.setState({ toAvatar: result.data.myUserDataForIMs[0].picture_thumbnail });
});
If there's a better/more efficient way, please post it.
You can do this by passing Apollo's refetch() method into your component's props alongside the data:
const withUserInfoForIMs = graphql(GET_MY_USERINFOFORIMS_QUERY, {
options({ userID }) {
return {
variables: { userID: `${userID}`}
};
},
props({ data: { refetch, loading, myUserDataForIMs } }) {
return { refetch, loading, myUserDataForIMs };
},
name: 'GET_MY_USERINFOFORIMS_QUERY',
});
...then somewhere in your component, you can refetch the data "manually":
theUserWasChangedSomehow(userID) {
this.props.refetch({ userID });
}

GraphQL how to mutate data

I have a basic schema for mutating some data which looks like
const schema = new graphql.GraphQLSchema({
mutation: new graphql.GraphQLObjectType({
name: 'Remove',
fields: {
removeUser: {
type: userType,
args: {
id: { type: graphql.GraphQLString }
},
resolve(_, args) {
const removedData = data[args.id];
delete data[args.id];
return removedData;
},
},
},
})
});
Looking around google I cant find a clear example of the example query which needs to be sent to mutate.
I have tried
POST -
localhost:3000/graphql?query={removeUser(id:"1"){id, name}}
This fails with error:
{
"errors": [
{
"message": "Cannot query field \"removeUser\" on type \"Query\".",
"locations": [
{
"line": 1,
"column": 2
}
]
}
]
}
In order to post requests from the front-end application it is recommended to use apollo-client package. Say i wanted to validate a user login information:
import gql from 'graphql-tag';
import ApolloClient, {createNetworkInterface} from 'apollo-client';
client = new ApolloClient({
networkInterface: createNetworkInterface('http://localhost:3000/graphql')
});
remove(){
client.mutate({
mutation: gql`
mutation remove(
$id: String!
) {
removeUser(
id: $id
){
id,
name
}
}
`,
variables: {
id: "1"
}
}).then((graphQLResult)=> {
const { errors, data } = graphQLResult;
if(!errors && data){
console.log('removed successfully ' + data.id + ' ' + data.name);
}else{
console.log('failed to remove');
}
})
}
More information about apollo-client can be found here
Have you tried using graphiql to query and mutate your schema?
If you'd like to create a POST request manually you might wanna try to struct it in the right form:
?query=mutation{removeUser(id:"1"){id, name}}
(Haven't tried POSTing myself, let me know if you succeeded, i structured this out of the url when using graphiql)
You have to explicitly label your mutation as such, i.e.
mutation {
removeUser(id: "1"){
id,
name
}
}
In GraphQL, if you leave out the mutation keyword, it's just a shorthand for sending a query, i.e. the execution engine will interpret it as
query {
removeUser(id: "1"){
id,
name
}
}
cf. Section 2.3 of the GraphQL Specification
const client = require("../common/gqlClient")();
const {
createContestParticipants,
} = require("../common/queriesAndMutations");
const gql = require("graphql-tag");
const createPartpantGql = async (predictObj) => {
try {
let resp = await client.mutate({
mutation: gql(createContestParticipants),
variables: {
input: {
...predictObj,
},
},
});
let contestParticipantResp = resp.data.createContestParticipants;
return {
success: true,
data: contestParticipantResp,
};
} catch (err) {
console.log(err.message)
console.error(`Error creating the contest`);
return {
success: false,
message: JSON.stringify(err.message),
};
}
};

Resources