how to pass the variables dynamic in GraphQL? - reactjs

what changes need to perform the code:
const data = client.mutate({
mutation: (Query)
});
let Query = gql`
mutation{
create(input:{
department:"Tester",
code:"Tester"
}
)
{
code,
details,
description,
}
}`
console.log(data, "data")
how to pass input dynamically? I have my input as:
var department = {
department:"Tester",
code:"Tester"
}

I haven't tested it, but it will work.
in react apollo-client
import { gql, useMutation } from '#apollo/client';
const Query = gql`
mutation Create($department: String!, $code: String!) {
create(department: $department, code: $code) {
code
details
description
}
}
`;
const [create] = useMutation(Query);
create({ variables: { department: department_value, code: code_value } });
other way
const departmentValue = "Tester"
const codeValue = "Tester"
client.mutate({
variables: { department: departmentValue, code:codeValue },
mutation: gql`
mutation Create($department: String!, $code: String!){
create(department: $department, code: $code){
code
details
description
}
}
`,
})
.then(result => { console.log(result) })
.catch(error => { console.log(error) });

Related

Can't send data to graphQL database from next.js app

I am making a Reddit Clone. I have gotten to the point of implementation of SQL, so I am using graphQL and to make this easier Stepzen for endpoints. The following code is my Post Box for the reddit site along with graphQL, Mutations.ts and Queries.ts.
I have added Apollo Client and Toaster as well.
The problem seems to be occurring in my PostBox.tsx, It is coming from within my onSubmit function. As the Try/Catch runs, it triggers the error and catches it.
In the console my formData is a success and the console Log immediately inside the try works, but nothing else.
PostBox.tsx
import { useSession } from 'next-auth/react';
import React, { useState } from 'react';
import Avatar from './Avatar';
import { LinkIcon, PhotographIcon } from '#heroicons/react/outline';
import { useForm } from 'react-hook-form';
import { useMutation } from '#apollo/client';
import { ADD_POST, ADD_SUBREDDIT } from '../graphql/mutations';
import client from '../apollo-client';
import { GET_SUBREDDIT_BY_TOPIC } from '../graphql/queries';
import toast from 'react-hot-toast';
type FormData = {
postTitle: string;
postBody: string;
postImage: string;
subreddit: string;
};
function PostBox() {
const { data: session } = useSession();
// console.log(session);
//
const [addPost] = useMutation(ADD_POST);
const [addSubreddit] = useMutation(ADD_SUBREDDIT);
//
const [imageBoxOpen, setImageBoxOpen] = useState<boolean>(false);
const {
register,
setValue,
handleSubmit,
watch,
formState: { errors },
} = useForm<FormData>();
const onSubmit = handleSubmit(async (formData) => {
console.log(formData);
console.log('form data');
const notification = toast.loading('Creating new post...');
console.log(notification, 'notification');
try {
// query for subreddit topic
console.log('Test 1 Success');
//
// Error below: CL Test in line 42 is a success
const {
data: { getSubredditListByTopic },
} = await client.query({
query: GET_SUBREDDIT_BY_TOPIC,
variables: {
topic: formData.subreddit,
},
});
const subredditExists = getSubredditListByTopic.length > 0;
console.log('Test 2 Failed');
if (!subredditExists) {
// create subreddit
console.log('subreddit is new creating a new subreddit!');
console.log('Test 3 Failed');
const {
data: { insertSubreddit: newSubreddit },
} = await addSubreddit({
variables: {
topic: formData.subreddit,
},
});
console.log('Creating post...', formData);
const image = formData.postImage || '';
const {
data: { insertPost: newPost },
} = await addPost({
variables: {
body: formData.postBody,
image: image,
subreddit_id: newSubreddit.id,
title: formData.postTitle,
username: session?.user?.name,
},
});
console.log('New post added:', newPost);
} else {
// use existing
const image = formData.postImage || '';
const {
data: { insertPost: newPost },
} = await addPost({
variables: {
body: formData.postBody,
image: image,
subreddit_id: getSubredditListByTopic[0].id,
title: formData.postTitle,
username: session?.user?.name,
},
});
console.log('New post added', newPost);
}
setValue('postBody', '');
setValue('postImage', '');
setValue('postTitle', '');
setValue('subreddit', '');
toast.success('New Post Created!', {
id: notification,
});
} catch (error) {
toast.error('Whoops something went wrong!', {
id: notification,
});
}
});
queries.ts
import { gql } from '#apollo/client';
export const GET_SUBREDDIT_BY_TOPIC = gql`
query MyQuery($topic: String!) {
getSubredditListByTopic(topic: $topic) {
id
topic
created_at
}
}
`;
Mutations.ts
import { gql } from '#apollo/client';
export const ADD_POST = gql`
mutation MyMutation(
$body: String!
$image: String!
$subreddit_id: ID!
$title: String!
$username: String!
) {
insertPost(
body: $body
image: $image
subreddit_id: $subreddit_id
title: $title
username: $username
) {
body
created_at
id
image
subreddit_id
title
username
}
}
`;
export const ADD_SUBREDDIT = gql`
mutation MyMutation($topic: String!) {
insertSubreddit(topic: $topic) {
id
topic
created_at
}
}
`;
index.graphql ->There is more to this file but these are the only two I have changed, Supabase automatically built the rest
getSubredditList: [Subreddit]
#dbquery(
type: "postgresql"
schema: "public"
table: "subreddit"
configuration: "postgresql_config"
)
getSubredditListByTopic(topic: String!): [Subreddit]
#dbquery(
type: "postgresql"
schema: "public"
query: """
select * from "subreddit" where "topic" = $1
"""
configuration: "postgresql_config"
)
This is really upsetting me as I am not sure what is wrong. Thank you all for taking a look!

Can't get my reactive variable from graphql local query

I'm trying to setup a Apollo 3 local state with react. For an unknown reason my query does not work when I try to read a custom type (isAuthenticated query works well). Can you please help me to understand I literaly explored all the documentation and the link on internet about local state management.
Thank you
cache.js
import { InMemoryCache, makeVar, gql } from '#apollo/client'
export const isAuthenticatedVar = makeVar(!!localStorage.getItem('token'))
export const userVar = makeVar("")
export const cache = new InMemoryCache({
typePolicies: {
Query: {
fields: {
isAuthenticated: {
read() {
return isAuthenticatedVar()
}
},
user: {
read() {
return userVar()
},
__typename: 'User',
}
}
}
}
})
export const IS_AUTHENTICATED = gql`
query IS_AUTHENTICATED {
isAuthenticated #client
}
`
export const GET_LOCAL_USER = gql`
query GET_LOCAL_USER {
user #client
}
`
typedej.js
import { gql } from '#apollo/client'
export const typeDef = gql`
extend type User {
id: ID!
name: String!
surname: String!
email: String!
password: String!
phone: String!
adress: Adress!
isAdmin: Boolean!
isCoach: Boolean!
isManager: Boolean!
}
extend type Query {
isAuthenticated: Boolean!
user: User!
}
`
export default typeDef
test.js
const login = (email, password) => {
const emailLower = email.toLowerCase()
client.query({
query: LOGIN,
variables: { email: emailLower, password: password }
})
.then(result => {
console.log(result)
localStorage.setItem('token', result.data.login.token)
localStorage.setItem('userId', result.data.login.user.id)
isAuthenticatedVar(true)
userVar({ ...result.data.login.user})
console.log('USER VAR SETUP')
///Console.log show that userVar contains an object with all User data
console.log(userVar())
var test
try{
//test return NULL object
test = client.readQuery({ query: GET_LOCAL_USER}).user
}catch(error) {
console.log(error)
}
console.log('FETCH QUERY userVar')
console.log(test)
navigate("/")
})
.catch(error => {
console.log(error)
})
}
Tried several ways but can't find how to resolve this. I don't understand why documentation don't explain how to use with Object Type

How can i test the appearance of "message.success" from the library "antd"?

I am trying to test the appearance of a submit alert. Request to send a message to the server and process the response:
import { message } from "antd";
import { gql, useMutation } from "#apollo/client";
let [sendMessage, { loading }] = useMutation(
gql`
mutation sendMessage($name: String!, $email: String!, $message: String!) {
sendMessage(name: $name, email: $email, message: $message)
}
`,
{
onCompleted: () => {
message.success("success");
},
onError: (error) => {
message.warn(
error.message === "data"
? "bad data"
: "something wrong"
);
},
}
);
Below is the test I wrote for this code. But the test fails because there is no "success" text. But a div with the class "ant-message" is created.
import { MockedProvider } from "#apollo/client/testing";
it("click on butt", async () => {
let query = gql`
mutation sendMessage($name: String!, $email: String!, $message: String!) {
sendMessage(name: $name, email: $email, message: $message)
}
`;
let mocks = [{
request: {
query: query,
variables:{name:"Alex",email:"alex#gmail.com",message:"i need help"}
},
result: { data: { sendMessage:"success" } },
},
];
let { getByRole,findByText } = render(
<MockedProvider mocks={mocks}>
<HelpContainer />
</MockedProvider>
);
userEvent.click(getByRole("button"));
expect(await findByText("success")).toBeInTheDocument();
});
how to test it correctly?
needed to update version of "react-testing-library"

React Apollo Delay updating Cache After Mutation

I tried so hard to update Apollo cache after running Mutation, but i couldn't be able to remove 1 second delay after the mutation.
I followed 'ac3-state-management-examples' for solve this problem, but still couldn't find any problem.
This is my client-side code.
export const DELETE_ITEM_IN_CART = gql`
mutation DeleteItemInCart($cartItemId: String!) {
DeleteItemInCart(cartItemId: $cartItemId)
}
`;
export function useDeleteItemInCart() {
console.log(`DELETION START! ${Date()}`);
const [mutate, { data, error }] = useMutation<
DeleteItemInCartType.DeleteItemInCart,
DeleteItemInCartType.DeleteItemInCartVariables
>(DELETE_ITEM_IN_CART, {
update(cache, { data }) {
const deletedCartItemId = data?.DeleteItemInCart;
const existingCartItems = cache.readQuery<myCart>({
query: MY_CART,
});
if (existingCartItems && deletedCartItem && existingCartItems.myCart) {
cache.writeQuery({
query: MY_CART,
data: {
myCart: {
cartItem: existingCartItems.myCart.cartItem.filter(
t => t.id !== deletedCartItemId,
),
},
},
});
console.log(`DELETION OVER! ${Date()}`);
}
},
});
return { mutate, data, error };
}
And here's my server-side mutation
export const DeleteItemInCart = mutationField('DeleteItemInCart', {
args: {cartItemId: nonNull('String')},
type: nonNull('String'),
description: 'Delete an item in my cart',
resolve: (_, {cartItemId}, ctx) => {
const {prisma} = ctx;
try {
prisma.cartItem.delete({
where: {
id: cartItemId,
},
});
return cartItemId;
} catch (error) {
return cartItemId;
}
},
});
This is an example of Apollo-remote-state-mananagement
export const DELETE_TODO = gql`
mutation DeleteTodo ($id: Int!) {
deleteTodo (id: $id) {
success
todo {
id
text
completed
}
error {
... on TodoNotFoundError {
message
}
}
}
}
`
export function useDeleteTodo () {
const [mutate, { data, error }] = useMutation<
DeleteTodoTypes.DeleteTodo,
DeleteTodoTypes.DeleteTodoVariables
>(
DELETE_TODO,
{
update (cache, { data }) {
const deletedTodoId = data?.deleteTodo.todo?.id;
const allTodos = cache.readQuery<GetAllTodos>({
query: GET_ALL_TODOS
});
cache.writeQuery({
query: GET_ALL_TODOS,
data: {
todos: {
edges: allTodos?.todos.edges.filter((t) => t?.node.id !== deletedTodoId)
},
},
});
}
}
)
return { mutate, data, error };
}
Any advice?
1 second delay is inevitable using apollo cache?
I took a short video of my issue. i dont think it's inevitable...

How to refetch data with apollo refetchQueries and update loading status?

I have two Queries
const LIST_CARD_SETS_QUERY = gql`
{
cardSets {
id
name
}
}
`;
const ADD_NEW_CARD_SET = gql`
mutation($name: String!) {
createCardSet(name: $name) {
id
name
}
}`
And i try to refetch query LIST_CARD_SETS_QUERY after mutatuion like this
const { data, loading, error } = useQuery(LIST_CARD_SETS_QUERY, { notifyOnNetworkStatusChange: true });
const [onCreateCardSet] = useMutation(ADD_NEW_CARD_SET, { refetchQueries: [{ query: LIST_CARD_SETS_QUERY}]});
But loading status after mutation doesn't update.

Resources