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

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.

Related

Pass a query url param inside a graphql query (Next js)

I'm trying to get a content by the slug param in the url inside a next js app. When using getServerSideProps, I can pass a context.query.id, but here I'm trying to use getStaticProps. This is what I have so far:
export async function getStaticProps() {
const apolloClient = initializeApollo();
const { data } = await apolloClient.query({
query: SLUG_QUERY,
});
return addApolloState(apolloClient, {
props: {
data,
},
revalidate: 60,
});
}
const SLUG_QUERY = gql`
query ($id: String!) {
postCollection(slug: { eq: $id }) {
items {
title
shortDescription
heroImg {
url
}
createdAt
slug
}
}
}
`;
I'm struggling to understand How can I pass the conbtext.query.id as a parameter in the gql query.
Thanks for the help
pass context into your getStaticProps function
export const getStaticProps = async (context) => {
then move your query inside the getStaticProps to use it
postCollection(slug: { eq: $context.params.id }) {
Alternatively, if you prefer to keep your query outside of the function (if you are reusing it elsewhere for example), then just wrap it in a function that takes the id as a parameter
const getPostCollectionQuery = (id) => {
const SLUG_QUERY = gql`
query ($id: String!) {
postCollection(slug: { eq: $id }) {
items {
title
shortDescription
heroImg {
url
}
createdAt
slug
}
}
}
`;
return SLUG_QUERY;
};
and then you can call that from your getStaticProps function
const { data } = await apolloClient.query({
query: getPostCollectionQuery(context.params.id),
});

How to pass Unique Id in Graphql query

I'm trying to pass a unique id to a GraphQL query to get all data against the id. But when I print the console it shows undefined. Note that if I want to see all posts the then it becomes successful by another query.
in my query.js file I have written the below query:
export const Unique_Post_Query= gql`
query SampleQueries($id: ID!) {
post(_id: $id) {
id
data {
title
body {
text
}
}
}
}`;
and the below code from another file where I'm trying to see the result of the query:
const id='e42fd2b5-b84a-4417-afd2-36cdbaa204dd';
const { data , error,loading} = useQuery(Unique_Post_Query, { variables: {id ,}, });
//const { error, loading, data } = useQuery(PROFILE_QUERY);
console.log('yourrrrr f data',data);
Please check below reference
const id='e42fd2b5-b84a-4417-afd2-36cdbaa204dd';
const { loading, data } = useQuery(Unique_Post_Query, {
variables: { id: id},
});
useEffect(() => {
if (data && data?.post) {
console.log("data: ", data?.post);
}
}, [data]);

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 pass the variables dynamic in GraphQL?

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) });

Query data doesn't update after successful apollo cache write

I have a query on my App.js:
import { gql } from 'apollo-boost';
const ALL_ITEMS_QUERY = gql`
query ALL_ITEMS_QUERY {
challenges {
id
title
}
goals {
id
title
completed
createdAt
updatedAt
steps {
id
completed
title
}
}
}
`;
And i am looking to write a simple deleteGoal mutation:
const DeleteWrapper = (props) => {
const [deleteGoal, { data }] = useMutation(DELETE_ITEM_MUTATION, {
update(cache, payload) {
const data = cache.readQuery({ query: ALL_ITEMS_QUERY });
data.goals = data.goals.filter(
(goal) => goal.id !== payload.data.deleteGoal.id
);
cache.writeQuery({ query: ALL_ITEMS_QUERY, data });
},
});
}
The function returns the modified array correctly, but the item never disappears from the frontend list. I have a hunch that this is related to querying multiple categories at once (goals and challenges, rather than goals only).
Even though the cache seems to be modified correclty, why does the item never disappear, why does the re-render never happen?
After some trial and error I found out that I have to lay out the exact data object to the writeQuery function. I don't really understand why, since the challenges object was left untouched after the query. I have not been able to make this work otherwise.
const DeleteWrapper = (props) => {
const [deleteGoal] = useMutation(DELETE_ITEM_MUTATION, {
update(cache, { data: { deleteGoal} }) {
const { goals, challenges } = cache.readQuery({ query: ALL_ITEMS_QUERY });
const newArr = goals.filter((goal) => goal.id !== deleteGoal.id);
cache.writeQuery({
query: ALL_ITEMS_QUERY,
data: { challenges, goals: newArr },
});
},
});
}

Resources