Apollo Mutation - UI not updated after useMutation update - reactjs

Background: always able to make Apollo store cache updated, but not UI
Question:
what's the reason that makes the UI updated or not?
what's the right way to pass the data object in update?
"react": "~16.9.0"
"#apollo/react-hooks": "^3.1.3"
Both UI and cache updated codes in my project:
update: (store, { data: { newPhoto } }) => {
const { bookInfo } = store.readQuery({ query: GET_BOOK_BY_ID, variables: { bookId } });
bookInfo.photos = [...bookInfo.photos, newPhoto];
store.writeQuery({
query: GET_BOOK_BY_ID,
variables: { bookId },
data: {
bookInfo
}
});
}
In this line: bookInfo.photos = [...bookInfo.photos, newPhoto];, the bookInfo object is amended directly and just passed back to writeQuery's data
This doesn't look okay to me as I saw people saying it needs to be "immutable" or "passing new object", etc.

if you experience the same thing, please check following list:
go to check out https://github.com/apollographql/apollo-client/pull/4543. By applying the freezeResults & assumeImmutableResults into the ApolloClient will help detect the issue. For my case, the issue actually occurs inside the parent component, which I mutated the Apollo store objects, instead of the component that calling client.writeQuery, which is generally hard for others to notice too, in my opinion.
const client = new ApolloClient({
link: ...,
cache: new InMemoryCache({
freezeResults: true, // new
}),
assumeImmutableResults: true, // new
});
Ensure you mutate the data in an immutable fashion. (i.e. Apollo store object hasn't been changed until the end of update) https://github.com/immerjs/immer definitely helps to keep your change in immutable fashion. I used this to mutate my nested object and it's working so well.
Try to use client returned from the useMutation, then you get client.writeQuery to do the update. Although I'm not sure about this point, a lot of people spreading this message, probably help in some cases.
import { useMutation } from '#apollo/react-hooks';
import produce from "immer";
const [mutate, { client }] = useMutation(MUTATION_GQL);
const submit = () => {
mutate({
variables: { inputs },
update: (store, { data: { response }) => {
// get existing cache returned from the query
const cache = store.readQuery({ query: QUERY_GQL, variables: { id } });
// manipulate the cache in immutable fashion
const data = produce(cache, draftCache => {
draftCache.title = "new title";
draftCache.approval = response;
});
// write the cache back to that query
// REMEMBER the variables inside writeQuery too!
client.writeQuery({
query: QUERY_GQL,
variables: { id },
data,
});
}
})
}
Try to use useQuery to read the data from ApolloClient instead of readQuery so you will get the updated cache from Apollo's store

Related

Apollo Client fetchMore from useQuery does duplicate network request after every fetch

We have a web application. We have been extensively using Apollo + React's useQuery to give user infinite scroll experience. We recently realized that components were not loading assets after fetchMore was used second time. On a network tab, there was a constant loop of the first and second request.
After some debugging, I realized that I need to have a merge function in Apollo to merge data when we use fetchMore.
I changed code. Added AssetData in typePolicies to below:
export const getApolloClient = (): ApolloClient<NormalizedCacheObject> =>
new ApolloClient({
cache: new InvalidationPolicyCache({
typePolicies: {
AssetData: {
keyFields: [],
fields: {
assets: {
merge(existing = [], incoming: string[], { args }) {
return [...existing, ...incoming];
}
}
}
},
},
invalidationPolicies: {
types: {
Asset: {
timeToLive: 29 * 60 * 1000
}
}
}
}),
link: new HttpLink({ fetch })
});
Which helped to break the loop. But I still see that after every fetchMore requests, another duplicate network call for the original query does trigger. Which actually messes up entire merge function in Apollo. I will have so much of duplicate data. So many people have reported similar issues and I tried many proposed solutions [https://github.com/apollographql/apollo-client/issues/7307][1], [https://github.com/apollographql/apollo-client/issues/7939][2], [https://github.com/apollographql/apollo-client/issues/9668][3]
But nothing is helping me to fix it.
Here is my query:
const { loading, data, error, fetchMore, networkStatus } = useQuery<
AssetsQuery
>(assetsQuery, {
variables: {
role,
version: version,
offset: 0,
limit: 30,
region
},
fetchPolicy: 'cache-and-network',
nextFetchPolicy: 'cache-first',
});
In one of the thread apollo team mentioned that this issue is resolved in a new version 3.6.0. So, I also updated my apollo version from 3.2.0 to 3.6.9, but I still have same issue.
Please let me know if you have any further suggestions
[1]: https://github.com/apollographql/apollo-client/issues/7307 [2]: https://github.com/apollographql/apollo-client/issues/7939 [3]: https://github.com/apollographql/apollo-client/issues/9668

Graphql - Apollo Client/ React - Cache - fetchMore doesn't update the data state of the query

I try to implement cached pagination, in my react app using apollo client.
my query has filter argument, which should be the only argument that create a new key in the cache object.
for some reason, when fetchMore occurs with filter specified, the new data doesn't cause a re-render in the component.
I logged the existing and incoming argument in the merge function, and it seems that for each fetchMore that had filter, new data did arrive. so, i don't understand why the component didn't re-render.
to make things worst: calling fetchMore several times with or without filter send http request and merging the incoming data with the existing data. which i'd expect wouldn't happen as the client should see that it already has a key in the cache for that query with that key argument.
the following is the query:
query Shells($first: Int = 5, $offset: Int = 0, $filter: ShellFilter) {
shells(
orderBy: [STATUS_ASC, EXECUTION_FROM_DESC]
first: $first
offset: $offset
filter: $filter
) {
nodes {
...ShellData
}
totalCount
}
}
the apolloClient config is like this:
const client = new ApolloClient({
cache: new InMemoryCache({
typePolicies: {
Query: {
fields: {
shells: {
keyArgs: ['filter'],
merge: (existing, incoming) => {
console.log('existing:', existing, 'incoming:', incoming);
return mergeObjectsAndNestedArrays<ShellsConnection>(
existing,
incoming,
'nodes',
);
},
},
},
},
},
})
and the component that displays it:
const ControlCenter = () => {
const { showModal } = useModalContext();
const [page, setPage] = useState(1);
const { data, loading, fetchMore } = useShellsQuery();
const [query, setQuery] = useURLQuery();
const onCounterpartiesChange = async (counterparties) => {
await fetchMore({
variables: {
filter: { shellCounterParties: { some: { orgId: { in: '20584' } } } },
},
});
setQuery({ counterparties });
};
const shells = data?.shells?.nodes;
console.log('hello from shells:', shells);
these are the logs:
EDIT 1 - docs reference
Following the docs: https://www.apollographql.com/docs/react/pagination/key-args/#setting-keyargs
any argument can be used as the keyArgs: limit, offset and filter.
In the documentation examples, the arg used as the key is a primitive value, but in your case, the filter arg is an object. This could be causing apollo to see all results as the same cached version. If your data depend only on the orgID I think you could try the nested array notation to set that field as the key.
keyArgs: ["filter", ["shellCounterParties", ["some", ["orgId", ["in"]]]]]
or the custom function
keyArgs: (args, context) => args.filter.shellCounterParties.some.orgId.in
If you really need to cache according to the whole filter object, I guess the simplest way would be stringifying it
keyArgs: (args, context) => JSON.stringify(args.filter)
But to be sure how apollo is caching the data, I highly recommend you to try the apollo devtools
related: https://github.com/apollographql/apollo-client/issues/7314
I think the problem lies where you have defined typePolicies in your code with keyArgs: ['filter'].
Please check official docs:
https://www.apollographql.com/docs/react/caching/cache-configuration/#customizing-cache-ids
You can customize how the InMemoryCache generates cache IDs for individual types in your schema
This is helpful especially if a type uses a field (or fields!) besides id or _id as its unique identifier.
Based on this, you have defined filter as a unique identifier even though that is a variable which is used for filtration purpose. It is not a field to customize the cache but a variable.
Note that these keyFields strings always refer to the actual field names as defined in your schema, meaning the ID computation is not sensitive to field aliases.
My suggestion first of all would be to modify the configuration that you have set up and see if it helps?
Instead of fetchMore use refetch inside useEffect and pass there new variables
function photo({ id }) {
const { data, refetch } = useQuery(GET_PHOTO, {
variables: { id },
});
useEffect(() => {
refetch({ id })
}, [id])
}

Why react useQuery() doesnt fetch the newest data after a mutation?

I have a code like this
const [inputComment, setInputComment] = useState('');
const [
commentPost,
{ data: data4, loading: loading4, errorCreate4 },
] = useMutation(COMMENT_POST);
const { error: error2, loading: loading2, data: data2 } = useQuery(
GET_POST_BY_ID,
{
variables: {
postid: item.id,
},
},
);
const doComment = () => {
commentPost({
variables: {
postId: item.id,
userEmail: email,
comment: inputComment,
},
})
.then(({ data }) => {
setInputComment('');
console.log('success');
})
.catch((e) => {
console.log('not success');
});
};
This is supposed to get the data, and when I do comment then it runs the mutation and re-render everything.
My problem is, it re-render alright BUT the data that the useQuery fetch is not the newest data a.k.a the data before I add a new comment.
Does anyone know how to fix this problem??
Please help :(
Your mutation modifies data on the server side.
Once your mutation is done, you should refetch your data in order to get the modified version in your local cache on the client side.
By guessing how your mutation and query actually work, here is how it would look like:
const [
commentPost,
{ data: data4, loading: loading4, errorCreate4 },
] = useMutation(COMMENT_POST, {
refetchQueries: [
{ query: GET_POST_BY_ID, variables: { postid: item.id } }
]
});
Otherwise, intead of refetching from the server, you could update the local cache directly.
More info can be found here in the official documentation.
I assume commentPost is an insert operation, not an update of a single record. In this case, Apollo useMutation will not update the cache for you. You need to modify the cache yourself. The official Apollo documentation has covered this use case with an example. You may want to revise the usage of writeFragment as well.
Below are directly from apollo docs on cache update for list fields.
In most cases, a mutation response should include any object(s) the
mutation modified. This enables Apollo Client to normalize those
objects and cache them according to their __typename and id fields (by
default).
...
When a mutation's response is insufficient to update all modified
fields in your cache (such as certain list fields), you can define an
update function to apply manual changes to your cached data after a
mutation.
const [addTodo] = useMutation(ADD_TODO, {
update(cache, { data: { addTodo } }) {
cache.modify({
fields: {
todos(existingTodos = []) {
const newTodoRef = cache.writeFragment({
data: addTodo,
fragment: gql`
fragment NewTodo on Todo {
id
type
}
`
});
return [...existingTodos, newTodoRef];
}
}
});
}
});
EDIT
I noticed another answer suggests using refetch, which is not a bad option for starters. However, updating the cache is the recommended approach over refetch. You can refer to the Apollo blog article When To Use Refetch Queries in Apollo Client.
Below are some quotes you should note from this article.
If you’re just getting started with GraphQL, I think the mental model of passing in the queries that you’d like to re-run after a mutation is an easy one to wrap your head around.
...
The advantage here is that this approach is straightforward. The disadvantage is that we’re fetching the entire list of data again when we might not need to.
...
For a more efficient use of bandwidth and network round-trips, we can rely on cache normalization and update functions.

UseApolloClient query won't return fetchMore

I am working on project with Apollo on client side. I am using react-apollo-hooks on my client side. And I have a problem with useApolloClient.
When i fire query with my client I got in useApolloClient I don't get back all data I need. FetchMore is missing. If I use regular query (useQuery) I get that. But problem is I need to fire that query on click and i need to use one provided with apollo client.
I have this function for fetching data on click:
const bulkSearch = async data => {
setContent(<Spinner />);
showModal();
try {
const response = await client.query({
query: BULK_SEARCH_PRODUCTS,
variables: { data }
});
if (!response.loading) {
setContent(
<ProductsListDisplay
products={response.data.bulkSearch.products}
fetchMore={response.fetchMore}
count={{ total: 10 }}
/>
);
return 200;
}
} catch (err) {
return 400;
}
};
And response doesn't contain fetchMore.
On the other way classic query returns fetchMore.
const newdata = useQuery(BULK_SEARCH_PRODUCTS, {
variables: { data: { ids: ["536003", "513010"] } }
});
Some help ? Thank you!
According to the apollo-client docs, ApolloClient.query returns a Promise that resolves to an ApolloQueryResult, which is a simpler object that has only data, errors, loading, networkStatus, and stale as properties.
On the other hand, the render prop argument of react-apollo's Query component gets fed a much richer object, with fetchMore being one of its additional properties. If you want to do something similar using the raw ApolloClient object, you would have to use ApolloClient.watchQuery, which returns an ObservableQuery that you can subscribe to consume results. The benefit of this is that you have access to more methods, such as ObservableQuery.fetchMore.
Note this approach is fundamentally different than using ApolloClient.query, since that function requests one query and returns the result as a Promise, while ApolloClient.watchQuery consistently monitors your cache and pushes updated results to your subscribe method when the cache store changes, so it's a more complicated lifecycle. In general, if you're already using react-apollo or one of the #apollo/react-X packages, you probably want to stay away from ApolloClient.watchQuery, since the functionality from those libraries builds directly on top of it and is designed to be easier to consume.
Hope this helps!
You have to create your own FetchMore method for this. This has to be handled by you that's the safer you to go.
In my case I needed
fetchMore
Adding Infinite loading and should event deal with loading state as well.
Problem with default loading state is that it will be always false as return of promise.
When you use await client.query.
In our query we have cursor based pagination.
read this
Create Function that will trigger on scroll ( end of page )
Check on value of after and update it with state management
Loading as well as data also needs to be in state.
Code:
const fetchMoreFilteredData = async (after) => {
try {
setFilteredLoading(true); // set this state in order to show loading indicator
const { data, loading } = await client.query({
query: QUERY,
variables: {
after: after,
...all variables,
},
fetchPolicy: "network-only",
notifyOnNetworkStatusChange: true,
});
const {
query: {
pageInfo: { hasNextPage, endCursor },
},
} = data;
setFilteredData({
// update your data ...filteredData,
});
setHasNextPage(hasNextPage); // check if there is next page
setEndCursor(endCursor); // set end cursor for next page this will guide the query to fetch next page
setFilteredLoading(loading); // set loading state to false
} catch (error) {
error.graphQLErrors.map((error) => {
console.log("error", error.message);
});
setFilteredLoading(false);
} };
const handleLoadMore = () => {
hasNextPage && fetchMoreFilteredData(_endCursor);
};

Apollo can't access queryVariables in update: after a mutation

I am trying to use update: to update a query after performing a mutation. The problem is that the query in the store has several different variables applied and I would like to update the query and return it with the same variables.
I found in the docs that updateQueries has an option to include queryVariables which are the last set of variables that the query was executed with.
I have not found anything that describes how to retrieve the queryVariables or something like it from inside of update.
Inside of update: I can use
lastQuery = Object.keys(store.data.ROOT_QUERY).slice(-1)[0]
which will return a result like "userRecipes({"first":20,"minTime":0,"maxTime":500,"filterType":"Explore","searchTerm":""})"
The hacky way that I am doing this now is to parse that string to pull out the variables so I can finally use readQuery like so:
const lastQuery = Object.keys(store.data.ROOT_QUERY).slice(-1)[0]
const searchPosition = lastQuery.search("searchTerm")
const searchTerm = lastQuery.slice((searchPosition + 13),-3)
// also parsing the lastQuery string for filterType, minTime, maxTime
const data = store.readQuery({
query: QUERY_USER_RECIPES,
variables: {
filterType: filterType,
searchTerm: searchTerm,
minTime: minTime,
maxTime: maxTime,
}
});
This can't be the best way to do this. Is there a simpler way to access variables inside of update?
It seems like there should be a way to read the existing query and variables that are in the store without passing variables with readQuery.
Thanks for taking a look at this issue!
Version
apollo-client#1.4.0
react-apollo#1.4.2
For apollo 2, but should be the same in 1.x
In the docs, you see that you can also pass variables to readQuery.
Here is an example where a user can book an event clicking a BookEvent component, if the mutation succeeds, it is reflected automatically in the upper component EventDetail.
In the component that tiggers the mutation (BookEvent), I pass store and eventId to a function declared in the upper component (EventDetail) and passed through props of the child component:
const onClick = () => createEventTicketMutation({
variables: { eventId: event.id },
update: (store, { data: { createEventTicket } }) => {
updateStoreAfterBooking(store, event.id)
},
})
Here is the function that performs the cache update in the upper component:
const updateCacheAfterBooking = (store, eventId) => {
const data = store.readQuery({
query: EVENT_DETAIL_QUERY,
variables: { id: eventId },
})
data.eventDetail.bookings += 1
store.writeQuery({
query: EVENT_DETAIL_QUERY,
variables: { id: eventId },
data,
})
}
It is passed like so <BookEvent updateStoreAfterBooking={updateCacheAfterBooking} ... />.
Don't forget to pass also the needed variables to writeQuery.

Resources