Intended outcome:
I'm trying to authenticate a user and have it update my navbar (which uses the same query) to show different options whether the user is logged in or not.
Actual outcome:
Whats actually happening is, after refetching (during the login mutation), im getting new data from my query, and the network tab is showing it, store seems updated, however the component itself is still rendering stale data (outputted via console.log). Doing a hard refresh fixes the issue (since we get new data).
How to reproduce the issue:
I made a little demo video:
https://drive.google.com/file/d/1Zmp1nwJBYnkuO0Cr2x4jUSnY61REkD8X/view
To explain the justification, i have a user query here that checks at a high level:
const isLoggedInQuery = gql`
query isAuthenticated {
currentUser {
id
firstName
lastName
gender
location
password
email
permissions {
id
name
displayOrder
description
}
roles {
id
name
description
displayOrder
}
}
}
`;
export default graphql(isLoggedInQuery, {
name: "isLoggedInQuery"
})(Main);
If the user isn't authed it returns null
In my login component i have it like this:
this.props.mutate({
variables: { token },
refetchQueries: [
{
query: gql`
query isAuthenticated {
currentUser {
id
firstName
lastName
gender
location
password
email
permissions {
id
name
displayOrder
description
}
roles {
id
name
description
displayOrder
}
}
}
`
}
]
});
Versions
"react-apollo": "^2.1.4",
was able to solve by following this:
https://github.com/apollographql/react-apollo/issues/2070, for anyone else who stumbles on this issue. My initial result of the query was always a error, hence refetching didnt set it back into its loading state unless you set the query you were refetching to cache-and-network.
@kkotwal94 i'm seeing this same issue even though there were not any errors with the initial query
@stephenhandley maybe i could post some code to help with this, i don't know if it'll solve your issue.
Maybe you can post your code too so we can see whats up.
Initally, this was a apollo error in the query if I wasn't logged in (because, im not logged in :+1: ), so refetching didn't work. Look at the export at the bottom and I had to do that.
The query name isAuthenticated gets refetched from my login component rerendering all my components using that same query.
Header.jsx
import React, { Component } from "react";
import { Link, withRouter } from "react-router-dom";
import gql from "graphql-tag";
import { graphql, compose } from "react-apollo";
import { withStyles } from "@material-ui/core/styles";
import List from "@material-ui/core/List";
import ListItem from "@material-ui/core/ListItem";
import Button from "@material-ui/core/Button";
import headerLinksStyle from "./HeaderLinksStyle";
import { Dashboard, LockOpen, GetApp, Info } from "@material-ui/icons";
const isLoggedInQuery = gql`
query isLoggedInQuery {
token @client
}
`;
const loggedInMutation = gql`
mutation authToken($token: String!) {
assignAuthToken(token: $token) @client {
token
}
}
`;
const userQuery = gql`
query isAuthenticated {
currentUser {
id
firstName
lastName
gender
location
password
email
permissions {
id
name
displayOrder
description
}
roles {
id
name
description
displayOrder
}
}
}
`;
class HeaderLinks extends Component {
logout = () => {
localStorage.removeItem("auth_token");
this.props.mutate({
variables: { token: null }
});
this.props.history.push(`/`);
};
render() {
const { classes } = this.props;
const { token } = this.props.data;
const isLoggedIn = token;
console.log(this.props);
return (
<List className={classes.list}>
{isLoggedIn && (
<ListItem className={classes.listItem}>
<Link to="/dashboard" style={{ color: "inherit" }}>
<Button color="inherit" className={classes.navLink}>
<Dashboard className={classes.icon} />Dashboard
</Button>
</Link>
</ListItem>
)}
{!isLoggedIn && (
<ListItem className={classes.listItem}>
<Link to="/login" style={{ color: "inherit" }}>
<Button color="inherit" className={classes.navLink}>
<LockOpen className={classes.icon} />Login
</Button>
</Link>
</ListItem>
)}
{!isLoggedIn && (
<ListItem className={classes.listItem}>
<Link to="/signup" style={{ color: "inherit" }}>
<Button color="inherit" className={classes.navLink}>
<GetApp className={classes.icon} />Sign up
</Button>
</Link>
</ListItem>
)}
<ListItem className={classes.listItem}>
<Link to="/about" style={{ color: "inherit" }}>
<Button color="inherit" className={classes.navLink}>
<Info className={classes.icon} />About
</Button>
</Link>
</ListItem>
{isLoggedIn && (
<ListItem className={classes.listItem}>
<Button
color="inherit"
className={classes.navLink}
onClick={event => {
this.logout();
}}
>
<LockOpen className={classes.icon} />Logout
</Button>
</ListItem>
)}
</List>
);
}
}
export default compose(
graphql(isLoggedInQuery),
graphql(loggedInMutation),
graphql(userQuery, {
name: "user",
options: { fetchPolicy: "cache-and-network" }
}),
withStyles(headerLinksStyle),
withRouter
)(HeaderLinks);
Login.jsx:
const LOGIN = gql`
mutation login($email: String!, $password: String!) {
login(email: $email, password: $password) {
token
user {
email
firstName
lastName
location
pictureUrl
websiteUrl
roles {
id
name
description
displayOrder
}
permissions {
id
name
description
displayOrder
}
}
}
}
`;
login = (event, loginMutation) => {
const { email, password } = this.state;
console.log(this.props);
loginMutation({ variables: { email, password } }).then(({ data }) => {
const { token } = data.login;
this.saveUserToken(token);
this.props
.mutate({
variables: { token },
refetchQueries: () => ["isAuthenticated"]
})
.then(data => {
this.props.history.push(`/`);
});
});
};
I omitted a lot from the second file, but i think that was all that was needed to be shown (let me know if you want to see the whole file).
I am also getting this same error. The solution suggested by @kkotwal94 did not work for me.
can you be a bit more specific, post some code maybe, the exact scenario, so we can disect it, maybe find the true root of the error?
@kkotwal94 Following the link your posted, it seems that it was problem in the react-apollo
package. Scrolling down, it seem to be fixed but not yet released.
As for my issue, I verified that the incoming GQL data was updated. It's just the component that was not updating.
Im guessing this component is trying to fetch data? (So a query?) in my case it works for me so im trying to figure out the difference. If it was a mutation thats updating data then are you updating the cache (if you are manipulating the cache) or are you doing a refetch?
Yeah I'm not seeing an error in my queries. Basically a mutation is run and I can verify via the chrome network tab that the updated data is arriving, however even with refetchQueries set, the component is still displaying stale data.
@kkotwal94 I am not doing query. I am doing a mutation and have the same problem as @stephenhandley.
and the query thats being refetched has this option?
graphql(userQuery, {
name: "user",
options: { fetchPolicy: "cache-and-network" }
}),
neither of the suggestions mentioned in https://github.com/apollographql/react-apollo/issues/2070 (changing fetchPolicy
or passing variables to Query i.e {v: Math.random()}
) helped with the issue.
:man_shrugging: Maybe we can compare versions and setup?
here's relevant apollo/react libs I'm using
"apollo-boost": "0.1.5",
"graphql": "0.13.2",
"graphql-tag": "2.9.2",
"react": "16.3.2",
"react-apollo": "2.1.3",
"react-dom": "16.3.2"
For what its worth I think enough people are seeing this issue that's there's something up with how they're updating the cache.
https://github.com/apollographql/apollo-client/issues/3573
This appears to be related as well
https://github.com/apollographql/apollo-client/pull/3169
Would be awesome if an ApolloClient maintainer could weigh in on this...
Same for me. I have a complex query (custom sorting based on several options) so updating the store manually is not an option, unfortunately. My mutation is successful, but when I run refetchQueries
(or this.props.data.refetch() explicitly in the update
function), my UI stays stale. If I look in the network tab I can see that the refetch actually happened and the dataset plus my new item created from my mutation was fetched.
Edit: Looks like I can get it to update the UI with an explicit call to refetch
in the update
function if I have the property fetchPolicy
set to cache-and-network
on my list. However refetchQueries
still is not working as mentioned.
I had a simple, client side query. When i modified the data model to no longer update an @client property, I got no results back from the query. I was not using a schema for the client properties. When i removed that property from the query, all my results came back.
@hwillson , i think it is realted to https://github.com/apollographql/react-apollo/issues/2070
Any update on this issue? This is breaking my app right now. This issue isn't fixed in 2.1.11
too
I have the same problem as @Auchindoun. An explicit refetch works but refetchQueries
doesn't.
This is a huge blocker bug for our app too.
Edit: it DOES seem to work if i use a function. So replacing
refetchQueries: [ 'getBookings' ]
with
refetchQueries: () => [ 'getBookings' ]
does update the UI for me properly with the previous variables with which getBookings had been called.
I'm using the graphql HOC btw.
Nobody from from apollo team cares
On Tue, Sep 4, 2018, 8:38 PM sandorvasas notifications@github.com wrote:
This is a huge blocker bug for our app too.
—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
https://github.com/apollographql/apollo-client/issues/3633#issuecomment-418351202,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AAK0caVZuUMwL7UjM7aSkhCBocuncROcks5uXnRAgaJpZM4U8aBZ
.
@iamrommel We care! If someone here can provide a small, runnable reproduction that clearly demonstrates this issue, that would greatly help with getting this resolved.
@hwillson, it's been two months and this issue has not been closed, if you really cares, you should check it out on your testing lab and verify it, If you cannot reproduce this, then close this issue so it wont be a clutter. i dare you to close this issue.. :)
@iamrommel The Apollo team is small (we're hiring!). Anything the community can do to help reduce the amount of time issue triaging / bug fixing takes (like creating reproductions) goes a long way towards helping get issues resolved faster. If someone in this issue thread is able to help out, that would be awesome.
Hey guys. It seems that I've found the trick to reproduce the issue. Here is my code:
const GET_VEHICLES = gql`
query getAllVehicles {
getVehicle {
id
...
}
}
`;
...
<VehiclesQuery query={GET_VEHICLES}>
{({ data, loading, error }) => {
const list = _.get(data, 'getVehicle');
if (loading || error || (!list || list.length < 1)) {
return <VehicleSlideView list={[]} />;
}
return <VehicleSlideView list={list as Vehicle[]} showAddCard={false} />;
}}
</VehiclesQuery>
The first time when entering this page and if not signed in, the query will fail due to 401. After that If I signed in and add a vehicle via a mutation like this:
<MutationAddVehicle
mutation={ADD_VEHICLE}
variables={{ vehicle: this.state.carData }}
onCompleted={this.addVehicleSuccess}
refetchQueries={[{ query: GET_VEHICLES }]}
>
...</MutationAddVehicle>
When user trigger the mutation the expected behavior is in the VehiclesQuery the list will rerender due to the refetchQueries in mutation. However nothing happened.
The magic thing happens when I set the default state of the apollo-link-state into this:
const defaultState = {
getVehicle: []
};
instead of this:
const defaultState = {};
It seems that if the first time the query is not successfully fired and no default state in link-state is provided for this query, all the refetchQueries and writeCache that associated with it will not work as expected.
Hope it will be helpful.
This is a huge blocker bug for our app too.
Edit: it DOES seem to work if i use a function. So replacing
refetchQueries: [ 'getBookings' ]
with
refetchQueries: () => [ 'getBookings' ]
does update the UI for me properly with the previous variables with which getBookings had been called.
I'm using the graphql HOC btw.
This solves my problem completely.
This is a huge blocker bug for our app too.
Edit: it DOES seem to work if i use a function. So replacing
refetchQueries: [ 'getBookings' ]
with
refetchQueries: () => [ 'getBookings' ]
does update the UI for me properly with the previous variables with which getBookings had been called.
I'm using the graphql HOC btw.
Oh wow this did the trick. The docs technically do have it correct, but some practical examples would be extremely helpful.
This is a huge blocker bug for our app too.
Edit: it DOES seem to work if i use a function. So replacing
refetchQueries: [ 'getBookings' ]
with
refetchQueries: () => [ 'getBookings' ]
does update the UI for me properly with the previous variables with which getBookings had been called.
I'm using the graphql HOC btw.
This worked. But is this the best way to do this?
Does this work with object arrays?
```
() => [
{
query: QUERY_SUMMARY,
variables: { id }
},
...
]
````
@arvinsim
No, I have tried.
But with the refetch function from another query it works, I use graphql
HOC:
compose(
graphql(TheOtherQuery, {
options() {
return {
variables: { name: 'A' },
}
},
props({ data: { refetch } }) {
return {
refetch,
}
}
}),
graphql(TheMutation, {
props({ mutate, ownProps: { refetch } }) {
return {
customMutate: () =>
mutate({
variables: { money: 100 },
update() {
refetch({ name: 'B' }); // <= HERE
}
})
};
}
}),
)
Guys,
I had the exact same issue. But as @kkotwal94 mentioned if you add fetchPolicy="cache-and-network"
it works perfectly.
I set my Mutation:
Component A
<Mutation mutation={YOUR_MUTATION} refetchQueries={() => [{ query: YOUR_GUERY, variables: { whatever } }]}>
I set my Query:
Component B
<Query query={YOUR_GUERY} variables={{ whatever }} fetchPolicy="cache-and-network">
The component A redirects to Component B with the updated values.
Hope it helps.
@AdrienFromToulouse mentioned the almost right solution for me.
This does not work:
YOUR_GUERY === products
const PRODUCTS_QUERY = gql`
{
products {
id
name
dealer
}
}
`;
Refactor to
YOUR_GUERY === getProducts
const PRODUCTS_QUERY = gql`
query **getProducts** {
products {
id
name
dealer
}
}
`;
Hope it helps.
OK, I think I've found some clues. It may be a regression bug.
In apollo-client, the function-style refetchQueries would become a string array, and then resolve through refetchQueryByName
.
And in react-apollo, the string array will try to resolve from this.context.operations
first.
However, the operation cache only has query
and lost the variables
! So you will see a query with empty variables if you pay attention.
The setOperations
from Qury#updateQuery
has the plain query
and variables
, but then, the Query#getQueryResult->initializeQueryObservable
passed the query as DocumentNode
and no variables!
And after a deeper investigation, it turns out that I have two same name queries, and one is skipped. The skipped one updates the operation without variables!
@hwillson, do I make myself :100: clear?
Yes, I too am seeing that if the variables are in any way different, the UI does not update.
Sen beni
If anyone here is able to provide a small, runnable reproduction that shows this happening, that would greatly help with troubleshooting. Thanks!
We were experiencing this issue on our team and we were able to resolve it by adding awaitRefetchQueries: true
to the options. I believe that may be the default in the latest version of Apollo, but it wasn't on the version we are using.
@hwillson
I hope this reproduction is helpful: https://github.com/arist0tl3/apollo-client-test
I think it pretty clearly demonstrates very different behavior when passing an array vs passing a function to refetchQueries
.
Notably:
Queries with the same name are correctly refetched _only_ when passing a function - when passed an array, only the first "found" query is refetched.
An unwatched query is correctly marked as stale and refetched _only_ when passing an array - when passed a function, the query is never refetched.
I've tried digging deeper but haven't been able to get yarn link
to play well with the apollo-client
packages =/
@hwillson - The code for the new Apollo Tutorial has this issue too!!! Well, it seems like it does. 😃
If you go to a "launch" and add it to the cart, then try to remove it from the cart, internally everything works great, but the UI isn't updating properly (i.e. the "Remove from cart" button is still shown.) This error goes through the app too, like when looking at the profile and switching to a booked launch. Unbooking that launch then shows a "Remove from cart" button, even though there is nothing in the cart to remove. React still has that launch as "in the cart".
I also tried some of the solutions mentioned here and none helped.
Hope I could help!
Scott
If my understanding of the problem is correct, then I believe this issue is fixed with alpha 2?
https://github.com/apollographql/apollo-client/commit/eb808196dc6e2bce92b46cc0161c425d0055f40f
I'll check to see, when I get home.
Scott
As @charlex pointed out, if query's variables change in any way, the UI does not update. Seems like apollo just doesn't consider the queries equal and therefore doesn't update UI. Is this behavior intended and queries must always be 100% equal or a bug?
Oh. And this issue isn't resolved with that commit/fix. At least not im my tests.
Scott
I might say something really obvious but I had this issue and for me the answer was in the documentation: https://www.apollographql.com/docs/react/essentials/mutations.html#update
Not every mutation requires an update function. If you’re updating a single item, you usually don’t need an update function as long as you return the item’s id and the property you updated.
I wasn't returning anything in my mutation, and now returning the id of the element plus all the element that I'm updating in the mutation solved my issue, no need to refetch and no need to use cache-and-network
flag that it means call the api everytime I mount the component (for me was a no go)
I've tried following solution to solve this, but all are failed
fetchPolicy="cache-and-network"
errorPolicy="ignore"
awaitRefetchQueries={true}
variables={{ v: Math.random() }}
refetchQueries: [ 'getBookings' ]
to refetchQueries: () => [ 'getBookings' ]
versions
"apollo-boost": "^0.1.23",
"graphql": "^14.1.0",
"graphql-tag": "^2.10.0",
"react": "^16.7.0",
"react-apollo": "^2.3.3",
@dbertella - What if the mutation is called in a child component? The resolver is returning the new data for the parent component, but the UI isn't getting updated. See:
of the full-stack tutorial as an example of what I mean. If you run the app and server in the tutorial, add a space flight/ mission to your shopping cart, then go to the cart and remove it, the mission and the remove button stay instead of the mission being removed from the cart. (in the background, the mission is removed from the cart).
Scott
Not sure about that, I'm not that expert in gql and apollo, but can it be that this mutation doesn't return an id? Read the doc carefully: as long as you return the item’s *id* and the property you updated
Apparently id is important here, and if I'm not mistaken in that particular mutation you pointing at id is not returned, can you check?
It returns the whole cart object, either with the new mission added, or the mission deleted. The logic is based off of ids, so the ids are there. It's just not one id, but possibly none or more than one.
I guess the question should be, if the Apollo cache is updated, will the UI displaying that data be updated automatically too? Or does something else need to be triggered? I'm far from an Apollo expert and even farther from a Apollo React expert. 😁
Scott
I'm seeing the same behavior, though a slight variation that may help the Apollo team. In my case, my UI component (Angular) has a selection list/drop down. For the selected item, my mutation updates some attributes and executes a refetchqueries. The mutation and refetchquery succeeds ( I can verify this in the network tab) but the UI does not update for the updated attributes. If I navigate to another item in the selection list and then navigate back to the same item as before, the UI updates and shows the updated attributes - mind you there are no additional graphql operations involved after the mutation/refetchqueries as part of the update. It almost seems like the refetchqueries succeeds but the cache update is queued past some operation.
I've got a Query component defined like so:
<Query query={qVarDataOptions} fetchPolicy='cache-and-network'>
{
/* eslint-disable-next-line object-curly-newline */
({ loading, error, data, refetch }) => {
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error.toString()}</p>;
return <form id="var_data" style={{ width: '40%' }}>
<table style={{ ...tableStyle, display: 'block', paddingBottom: '1em' }}>
<tbody>
<tr>
<th style={cellStyle}>name</th><th style={cellStyle}>description</th><th style={cellStyle}>setup charge</th><th style={cellStyle}>Delete?</th>
</tr>
{data.options ? <VarDataRows options={[...data.options.varData, ...this.state.additionalRows]} /> : null}
</tbody>
</table>
<this.Add addRow={() => this.addRow(ROWDATA)} />
<Submit clear={this.clearAdditionalRows} refetch={refetch} {...this.props} />
<Cancel {...this.props} />
</form>;
}}
</Query>);
The number of rows can be up to, oh, 40, and # of fields(columns) no more than 25. For updates, I'm just flagging the changes in the UI and then document.querySelectorAll() to find them for a bulk operation:
const UPSERT = gql`
mutation upsert($type: String!, $options: [InputOption]!) {
upsertOptions(optionType: $type, options: $options)
}
`;
const changes = (option) => {
const obj = {};
const inputs = option.parentNode.querySelectorAll('input[type=text]');
inputs.forEach((i) => {
const { name, value } = i;
obj[name] = value;
});
return obj;
};
const upsertEm = () => {
const opts = document.getElementsByName('changed');
const changed = [];
opts.forEach((o) => {
if (o.dataset.changed === 'true') {
changed.push(changes(o));
}
});
if (changed.length) {
const vars = { variables: { type, options: changed } };
mUpsert(vars);
}
return changed.length;
}
...
evt.preventDefault();
deleteEm();
upsertEm();
refetch();
returnTo(CALCULATOR);
After the insert, I navigate back to the home page, which has one query to refetch all the data it needs (which would include changes).
<Query
query={qOptionsAndCostFactors}
>
{({
loading, error, data, networkStatus,
}) => {
// console.log(props.setPage);
**if (networkStatus === 4) return <p>Refetching...</p>;**
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error.toString()}</p>;
...
I added the line in bold to handle the problem where I was not getting (at least some) data back. That helped mostly, but occasionally I still get an error regarding missing data in the query result.
I found that if I put a setTimeout() ahead of the page return, that seems to solve the issue, but that's pretty unreliable as well due to factors like network lag.
Hopefully @hwillson can take a look at this, once 2.5 beta is released. To me, this is either something very silly we're missing, or a big red no-go for Apollo Client, especially when the tutorial that's supposed to teach every one how great Apollo is, doesn't work.
Scott
Hey there, seems like my solution: https://github.com/apollographql/apollo-client/issues/1900#issuecomment-315372017
Does not work in the newest version of apollo-client. Has anybody put effort into creating a failing test case?
Edit: It actually works. Was related to not passing in the correct variables.
My use case is two tabs under which you can do a mutation that should update queries on both tabs.
For me https://github.com/apollographql/apollo-client/issues/3633#issuecomment-418351202 solution only helps if the component that uses the query is currently visible.
The only way I found of updating an already rendered out-of-sight query-driven component is to use fetchPolicy="cache-and-network"
which to me seems like a suboptimal solution because it hits the server every time a user switches tabs.
Let me know if you need a runnable project for that use case, I can spend some time on the weekend.
Why isn't there just a reload method that we can call or trigger on the Query objects? Why all the complexity?
@optimuspaul There is a refetch method supplied by Query components:
https://www.apollographql.com/docs/react/essentials/queries.html#refetching
refetchQueries are, as I understand it, basically meant to help you by not forcing you to pass that function around your app like a strand of spaghetti.
Anything new on this issue? We have this exact same behavior with apollo-angular, BUT only on IE11. It works on all other browsers. No error in the console.
Refetch may actually be happening, or perhaps happening only after the first refetch. I say this because I have a table where I can flag (through DOM) and delete records (through
Seems like it might be something to do with the initial state after page load.
In regarding to the refresh issue. I have the same trouble but with Angular 5 & 6 using Apollo Client 2.3. I think that is a sync issue.
No matter how do you write the refresh query, this works nice, but the mutation arrives first & the refresh milliseconds later without possibility to catch it: there is no an observable, or promise, of the refresh query to sync with it.
I resolve this issue with a separate query, changing the fetchPolicy
to network-only
. Its work like a charm.
@0zkr1 sadly network-only
doesn't fix it for me.
const tasksQuery = ({ match, render }) => {
return (
<Query
query={GET_TASKS_BY_USER_ID}
fetchPolicy="network-only"
variables={{ assigneeId: authStorage.get().id }}
render={render}
/>
);
};
const onUpdateTask = ({ render }) => <Mutation
mutation={UPDATE_TASK}
refetchQueries={
[
{
query: GET_TASKS_BY_USER_ID,
fetchPolicy: 'no-cache',
variables: {
assigneeId: authStorage.get().id,
},
},
]
}
awaitRefetchQueries={true}
>
{(mutation, result, ...rest) => {
return render({ mutation, result, rest })
}}
</Mutation>
Here is my code, which like everybody above is also hitting the db with the query, but not updating the UI.
I have played with all permutations of cache
, no-cache
etc to no avail.
@hutber I have had some success by setting partialRefetch={true} on the
Thanks @jdpaterson is this on the
I am encountering this as well on a record delete for a nested object (result has primary object with array of secondary objects. Calling refetch does not affect the UI of the list of secondary objects. Setting a pollInterval does refresh the UI. I am on react-apollo 2.2.4
Hi all,
I think I figured out how the refetchQueries
works with HOC. As you pass down in the variables that need to be assigned to your components, you need to pass also the gql
that contains your queries that you want to be refetched.
(yes it can contain many queries. They are distinguished with their names:
const MY_QUERIES = gql`
query QueryName1 {
// attributes to query
}
query QueryName2 {
// attributes to query
}
` ) ;
BUT this is not enough to trigger a refetch. You know that within your component you need to mutate
the variables that you passed down from the HOC right? OK, then you need ALSO to specify, with their names which queries within the gql
you want to be refetched.
So, in your component, you need to specify it like below:
this.props.mutate({
variables: {
_// assign your passed down variables here_
},
refetchQueries: ['QueryName1', 'QueryName2']
});
Btw, in my case, it works independent of the fetchPolicy
.
I hope it will help some of you guys.
Cheers!
This seems fragile to me. If I write a new query somewhere else in the app, how would I know which mutate operations need to have their refetchQueries list updated to include the new query?
Hi @JeffML,
I do not know if there is an easy way to figure this out. In my case, I am going through all my mutations to figure that out.
Guys,
I had the exact same issue. But as @kkotwal94 mentioned if you add
fetchPolicy="cache-and-network"
it works perfectly.I set my Mutation:
Component A
<Mutation mutation={YOUR_MUTATION} refetchQueries={() => [{ query: YOUR_GUERY, variables: { whatever } }]}>
I set my Query:
Component B
<Query query={YOUR_GUERY} variables={{ whatever }} fetchPolicy="cache-and-network">
The component A redirects to Component B with the updated values.
Hope it helps.
I could not get the UI to refresh after a successful mutation-and-then-query using the <Mutation refetchQueries={['queryName']} />
render prop pattern. My <Query />
component was high up in the app structure, with the <Mutation />
as a deeply nested child component.
I fixed the issue by following the instructions above. So that included adding the fetchPolicy
prop to the <Query />
AND changing the refetchQueries
prop to a function returning an array instead of just an array. refetchQueries={['queryName']}
became refetchQueries={() => ['queryName']}
Hope this helps! Here are my apollo versions:
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
└─ [email protected]
EDIT: It turns out the core issue I was facing was not apollo-related at all 🤦♂️. I wasn't seeing UI updates because I was copying data to React component state
rather than reading it from props
in a component that sits between the <Query />
and the <Mutation />
, meaning the updated query response only made it through the tree down to the offending component, which did not update itsstate
. Once I realized this, I was able to implement refetchQueries
as follows:
<Mutation refetchQueries={['queryName']} />
(it also still works for me by passing a function that returns an array)
And then I removed the fetchPolicy
prop from my <Query />
altogether, which means I am now using the default fetchPolicy
, cache-first
.
@madisonbullard that helps! My issue was that I was not passing the variables into the refetchQueries array object, your syntax helped me find that.
refetchQueries={() => [{ query: YOUR_QUERY, variables: { whatever } }]}
I think Apollo could in general put more emphasis on the fact that whenever you call a query, whether through refetch or through cache, the variables need to be re-specified.
Just ran into this as well. @jdpaterson's fix also worked for me! While just passing the name of a query to refetchQueries
worked elsewhere for us, and sometimes worked in the problem component under certain conditions, my suspicion is that there's some case of a cache miss for nested mutations unless you specify the full query and variables.
I had the same problem and I fixed it passing also the query variables
I might say something really obvious but I had this issue and for me the answer was in the documentation: https://www.apollographql.com/docs/react/essentials/mutations.html#update
Not every mutation requires an update function. If you’re updating a single item, you usually don’t need an update function as long as you return the item’s id and the property you updated.
I wasn't returning anything in my mutation, and now returning the id of the element plus all the element that I'm updating in the mutation solved my issue, no need to refetch and no need to use
cache-and-network
flag that it means call the api everytime I mount the component (for me was a no go)
This doesn't work for remove mutations. If you try to return the id, you'll get the error that no selection is allowed for delete mutations.
We had this problem, and it appeared to happen because we were routing at the same time as refetching Apollo data (using react-router). Our code looked like this:
this.props.userDataQuery.refetch();
this.props.history.goBack(); // can also put this before, same result
In the logs we saw:
The solution for us was to ensure the network query completed, before we did any routing or rerendering:
this.props.userDataQuery.refetch();
setTimeout(() => this.props.history.goBack(), 3000);
// or not changing route at all also worked
Not a great solution, but may provide some insight into what's going wrong.
Turns out for me it was a very simple change, though it meant going back through my components and tweaking them. The problem was graphql-lodash
.
As the update normally would take place automatically via the internal mapping that takes place you shouldn't ever need to pass a refetchQueries property unless you had some edge cases. But it turned out that by using graphql-lodash
inside my queries i was messing up with the mapping that react-apollo had created.
As soon as I removed this I rarely needed to use anything refetch
related. I should have actually been using update
seen here
Without Daniels help over at stackoverflow.com I never would have realised this, so props to him!!
None of the above solutions are working for me.
render() {
return (
<Mutation mutation={SAVE_ITEM}>
{(save) => (
<Mutation mutation={UNSAVE_ITEM}>
{(unSave) => (
<SaveButton
saved={this.state.savedButton}
onPress={() => {
this.setState((prevState) => ({
savedButton: !prevState.savedButton,
}));
return this.state.savedButton
? unSave({
variables: { nodeId: this.props.itemID },
refetchQueries: [{ query: GET_SAVED_LIST }],
})
: save({
variables: { nodeId: this.props.itemID },
refetchQueries: [{ query: GET_SAVED_LIST }],
});
}}
/>
)}
</Mutation>
)}
</Mutation>
);
}
fetchPolicy
on the original query is cache-and-network
It's not simply a UI mishap, I'm logging the data in cache every time I push the button. This must be a problem with refetchQueries
. I can't use update
because I don't have all the data required to update the query fully.
Did you check if you have graphql-lodash :p?
Did you check if you have graphql-lodash :p?
like as a dep? nah
yarn why v1.13.0
[1/4] 🤔 Why do we have the module "graphql-lodash"...?
[2/4] 🚚 Initialising dependency graph...
warning Resolution field "[email protected]" is incompatible with requested version "babel-core@^6.0.0"
warning Resolution field "[email protected]" is incompatible with requested version "babel-core@^6.0.0"
[3/4] 🔍 Finding dependency...
error We couldn't find a match!
✨ Done in 1.48s.
You shouldn't have to install any other packages for this expected functionality. You may as well put partialRefetch=true for a try. From docs:
"The default value is false for backwards-compatibility's sake, but should be changed to true for most use-cases"
You can also try passing in an empty object to variables in your original query and both refetchQueries calls: variables: {} .
You shouldn't have to install any other packages for this expected functionality. You may as well put partialRefetch=true for a try. From docs:
"The default value is false for backwards-compatibility's sake, but should be changed to true for most use-cases"
You can also try passing in an empty object to variables in your original query and both refetchQueries calls: variables: {} .
Neither worked. Here's the query one level up, the connected component, and the really dumb one a level down:
<Query
query={GET_SAVED_ITEMS}
fetchPolicy={'cache-and-network'}
partialRefetch
>
{({
data: { savedItems = [] } = {},
}) => {
const savedIDs = savedItems.map(
(savedItem) => savedItem.id
);
console.log(savedIDs);
return (
<SaveButtonConnected
saved={savedIDs.includes(item.id)}
itemID={item.id}
/>
);
}}
</Query>
render() {
return (
<Mutation mutation={SAVE_ITEM}>
{(save) => (
<Mutation mutation={UNSAVE_ITEM}>
{(unSave) => (
<SaveButton
saved={this.state.savedButton}
onPress={() => {
this.setState((prevState) => ({
savedButton: !prevState.savedButton,
}));
return this.state.savedButton
? unSave({
variables: { nodeId: this.props.itemID },
refetchQueries: [
{ query: GET_SAVED_ITEMS, variables: {} },
],
})
: save({
variables: { nodeId: this.props.itemID },
refetchQueries: [
{ query: GET_SAVED_ITEMS, variables: {} },
],
});
}}
/>
)}
</Mutation>
)}
</Mutation>
);
}
const SaveButton = memo(({ saved, onPress }) =>
saved ? (
<Button onPress={onPress}>
<ChannelLabel icon="save-solid" label={'Saved'} />
</Button>
) : (
<Button onPress={onPress} bordered>
<ChannelLabel icon="save" label={'Save Item'} />
</Button>
)
);
Solved my issue. My data connection was timing out, always leaving me with an empty array of savedItems
. cache-first
can't work because it doesn't know what the new cache is, cache-and-network
can't work because the network call on the end returning []
(timeout default) was wiping out the good data.
TL;DR use update
. refetchQueries
is only as reliable as your data connection, probably why it's not recommended for in place UI updates.
I've struggled to get updates working tbh. I had to move on and just settle for refetch even though I hate the fact that it does 2 queries for a single mutation :(
I'm having this problem too, any update?
I am having same issue. As workaround I am manually changing the state of the component to force the component to re-render on refetch
+1
We were rendering the mutation component with refetchQueries like so:
refetchQueries={[
{
query: QUERY,
variables: { location, tags }
}
]}
For us the issue was that the query had to be exactly the same in the refetch as when the component was first rendered. INCLUDING variables! Our variables were changing slightly between when the query was first run and on the refetch and was causing the re-render not to happen. This is definitely not the fix or a lot of the examples I'm seeing above, but hopefully it helps some people out.
Here's what I did
refetch
when you call useQuery
const { loading, error, data, refetch } = useQuery<...>(...)
set fetchPolicy
to cache-and-network
in this useQuery
invocation`
call refetch(...)
in the your mutation's onCompleted
callback (using useMutation
)
+1
if it helps: I observed that refetches were not fired, or their results not respected in the cache, if the event handler that fired the mutation also _synchronously_ navigated away, causing the component that owned the useMutation
hook to unmount.
If I removed the navigation and left the component mounted, or in some cases, await
'd the mutation first (with awaitRefetchQueries: true
), it would work as expected.
In my case, it smells like some Observable under the covers is getting unsubscribed on unmount (reasonable) and then dropping the handlers to refetch and cache on completion (not good).
The majority of this thread is people not understanding how Apollo works with its cache. There IS no bug here.
If you use any form of query with a fetchPolicy
that doesn't cache (like no-cache
), then refetchQueries
in a mutation won't do anything. Why? There is no cache to update from the mutation. If you want it to reload, you need to remount the component. (Yes, refetchQueries
is named poorly IMO).
What SHOULD you do? Use a query with a fetchPolicy
that has a cache option. If you need "always network" data, but still want this to work then use network-only
(which still caches) as the fetchPolicy
. It will keep a cache so it can see mutations, but it will always query the server on mount/render/cache-bust (the cache bust is what the refetchQueries
is doing).
fetchPolicy
with a cache to cause re-renders on mutations (list of fetchPolicy
options here)The other thing people seem to be missing is that QUERIES WITH VARIABLES ARE KEYED IN THE CACHE WITH THOSE VARIABLES. So if the variables change by the time you perform your mutation, then it won't know which key in the cache to update. Thus no re-render. If you want to use queries with changing variables, you need to customize your cache normalization behavior. See https://www.apollographql.com/docs/react/caching/cache-configuration/#data-normalization.
Read that again: if the variables change, the query won't refresh. This is because the cache considers those different queries, as it should.
I don't work for Apollo, but someone that does should come here, clarify what I said with more details/info, then close this issue. Also, they should update the documentation to be more clear about this subject. I get the frustration everyone has here. I felt it too until I saw the light.
@julian-sf
If you use any form of query with a fetchPolicy that doesn't cache (like no-cache), then refetchQueries in a mutation won't do anything.
What SHOULD you do? Use a query with a fetchPolicy that has a cache option. If you need "always network" data, but still want this to work then use network-only as the fetchPolicy.
Don't those two statements contradict each other? Or does network-only
still use a cache? If so that label is misleading.
Can you, or someone else, explain what I'm doing wrong below? Whether I use cache-and-network
or network-only
calls to insertConnection
do not trigger a re-render 90% of the time. Sometimes it works. If I uncomment the two commented lines, it works fine.
const {
loading,
error,
data,
// refetch,
} = useQuery(GET_BY_ID, {
variables: { id },
fetchPolicy: 'cache-and-network',
});
const [insertConnection] = useMutation(INSERT_CONNECTION, {
refetchQueries: () => [{
query: GET_BY_ID,
variables: { id },
}],
// onCompleted: refetch,
});
@julian-sf As I wrote on Feb 29th, 2019: We had the same problem (btw also with network-only), but the problem occurred only in IE. In Chrome everything was fine. So two browsers give two different outcomes and you want to tell me that it's not a bug but a feature?
I think the people in this issue are very frustrated when they find a bug that doesn't get fixed or even noticed and then someone tells them, they are just too stupid for the profession they do. Obviously something here went wrong, but it seems hard to reproduce.
For the people wondering how we solved this particular issue with Apollo: We don't use it anymore. Easy as that ;-)
I go with that @JustDoItSascha resolution, i turned away from using apollo because
there are several issues that are not getting fixed which are reported for
a very long time. I dont want to specify it one by one here as nobody
listens. What happens is not a "issue tab on github" but rather "ranting
tab" just like what i did. Hahaha
On Sat, Feb 15, 2020, 12:26 AM JustDoItSascha, notifications@github.com
wrote:
@julian-sf https://github.com/julian-sf As I wrote on Feb 29th, 2019:
We had the same problem (btw also with network-only), but the problem
occurred only in IE. In Chrome everything was fine. So two browsers give
two different outcomes and you want to tell me that it's not a bug but a
feature?I think the people in this issue are very frustrated when they find a bug
that doesn't get fixed or even noticed and then someone tells them, they
are just too stupid for the profession they do. Obviously something here
went wrong, but it seems hard to reproduce.For the people wondering how we solved this particular issue with Apollo:
We don't use it anymore. Easy as that ;-)—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/apollographql/apollo-client/issues/3633?email_source=notifications&email_token=AABLI4M7PS4GSFFHSLL52YLRC3AZ5A5CNFSM4FHRUBM2YY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOELZS3RY#issuecomment-586362311,
or unsubscribe
https://github.com/notifications/unsubscribe-auth/AABLI4NDL7BCFITEIR7HWLTRC3AZ5ANCNFSM4FHRUBMQ
.
The majority of this thread is people not understanding how Apollo works with its cache. There IS no bug here.
If you use any form of query with a
fetchPolicy
that doesn't cache (likeno-cache
), thenrefetchQueries
in a mutation won't do anything. Why? There is no cache to update from the mutation. If you want it to reload, you need to remount the component.What SHOULD you do? Use a query with a
fetchPolicy
that has a cache option. If you need "always network" data, but still want this to work then usenetwork-only
as thefetchPolicy
. It will keep a cache so it can see mutations, but it will always query the server on mount/render/cache-bust (the cache bust is what therefetchQueries
is doing).
This is what I just discovered last week to. I had to change my fetchPolicy
to network-only
to make it work.
I am not sure that is the only issue. I am using network-only
for one of my queries, and I see it fire in the network inspector (as in the original post) but the page doesn't (always) re-render.
In one case, I found that adding a useState(false)
and flipping it after awaiting the refetch _does_ re-render consistently, which smells very much like a React context state propagation bug.
Is there any official word on this issue from the apollo team?
This is a huge blocker bug for our app too.
Edit: it DOES seem to work if i use a function. So replacing
refetchQueries: [ 'getBookings' ]
with
refetchQueries: () => [ 'getBookings' ]
does update the UI for me properly with the previous variables with which getBookings had been called.
I'm using the graphql HOC btw.
My solution in Vue:
refetchQueries: () => this.getData(),
Simply call the fx which already has current pagination variables ;)
We were rendering the mutation component with refetchQueries like so:
refetchQueries={[ { query: QUERY, variables: { location, tags } } ]}
For us the issue was that the query had to be exactly the same in the refetch as when the component was first rendered. INCLUDING variables! Our variables were changing slightly between when the query was first run and on the refetch and was causing the re-render not to happen. This is definitely not the fix or a lot of the examples I'm seeing above, but hopefully it helps some people out.
This fixed the issue for me on the latest packages and react. refetchQuery MUST match the variables from when the query was last ran.
We were rendering the mutation component with refetchQueries like so:
refetchQueries={[ { query: QUERY, variables: { location, tags } } ]}
For us the issue was that the query had to be exactly the same in the refetch as when the component was first rendered. INCLUDING variables! Our variables were changing slightly between when the query was first run and on the refetch and was causing the re-render not to happen. This is definitely not the fix or a lot of the examples I'm seeing above, but hopefully it helps some people out.
Thank you so much! I spent the last 4 hours debugging this.
And when it comes to matching the variables, it appears that the types also matter. I was passing an int (42
) for my refetch query while the initial query has a string ("42"
) and that was preventing it from working.
This is a huge blocker bug for our app too.
Edit: it DOES seem to work if i use a function. So replacing
refetchQueries: [ 'getBookings' ]
with
refetchQueries: () => [ 'getBookings' ]
does update the UI for me properly with the previous variables with which getBookings had been called.
I'm using the graphql HOC btw.
This saved my day: thank you so much!
(and I am using "@apollo/client": "^3.0.0-beta.43" 🙌🏻)
Final result:
const [
bridgeDeviceUpdate,
{data: mutationData, loading: mutationLoading}
] = useMutation(MUTATION_BRIDGE_DEVICE_UPDATE,{
refetchQueries: () => [ 'userMe' ]
});
Shall we assume the Apollo team have completely forgotten about this? I appreciate the effort but there hasn't been an update for months and this is one of many important features within apollo-client...Due to this and the network-policy issues we might have to consider switching to an alternative library instead
😞
This is a huge blocker bug for our app too.
Edit: it DOES seem to work if i use a function. So replacingrefetchQueries: [ 'getBookings' ]
with
refetchQueries: () => [ 'getBookings' ]
does update the UI for me properly with the previous variables with which getBookings had been called.
I'm using the graphql HOC btw.This saved my day: thank you so much!
(and I am using "@apollo/client": "^3.0.0-beta.43" 🙌🏻)Final result:
const [ bridgeDeviceUpdate, {data: mutationData, loading: mutationLoading} ] = useMutation(MUTATION_BRIDGE_DEVICE_UPDATE,{ refetchQueries: () => [ 'userMe' ] });
@andlon10 I suggest you to use Apollo 3 beta. It works there👌
I'm in the process of safely migrating all of our render prop components to Apollo hooks, however once that's done I will definitely upgrade to 3, grazie 😃
@julian-sf
If you use any form of query with a fetchPolicy that doesn't cache (like no-cache), then refetchQueries in a mutation won't do anything.
What SHOULD you do? Use a query with a fetchPolicy that has a cache option. If you need "always network" data, but still want this to work then use network-only as the fetchPolicy.Don't those two statements contradict each other? Or does
network-only
still use a cache? If so that label is misleading.
Oh, their documentation is super misleading. But their documentation DOES state that network-only
calls the cache, although it stupidly says it in the no-cache
policy description:
https://www.apollographql.com/docs/react/api/react-apollo/#optionsfetchpolicy:
no-cache
: This fetch policy will never return your initial data from the cache. Instead it will always make a request using your network interface to the server. Unlike thenetwork-only
policy, it also will not write any data to the cache after the query completes.
https://github.com/apollographql/apollo-client/issues/3633#issuecomment-597851963
For us the issue was that the query had to be exactly the same in the refetch as when the component was first rendered. INCLUDING variables! Our variables were changing slightly between when the query was first run and on the refetch and was causing the re-render not to happen. This is definitely not the fix or a lot of the examples I'm seeing above, but hopefully it helps some people out.
This fixed the issue for me on the latest packages and react. refetchQuery MUST match the variables from when the query was last ran.
I mean that's what I said here, https://github.com/apollographql/apollo-client/issues/3633#issuecomment-585434640:
The other thing people seem to be missing is that QUERIES WITH VARIABLES ARE KEYED IN THE CACHE WITH THOSE VARIABLES. So if the variables change by the time you perform your mutation, then it won't know which key in the cache to update. Thus no re-render.
https://github.com/apollographql/apollo-client/issues/3633#issuecomment-586362311
@julian-sf As I wrote on Feb 29th, 2019: We had the same problem (btw also with network-only), but the problem occurred only in IE. In Chrome everything was fine. So two browsers give two different outcomes and you want to tell me that it's not a bug but a feature?
I think the people in this issue are very frustrated when they find a bug that doesn't get fixed or even noticed and then someone tells them, they are just too stupid for the profession they do. Obviously something here went wrong, but it seems hard to reproduce.
For the people wondering how we solved this particular issue with Apollo: We don't use it anymore. Easy as that ;-)
Oh, Apollo has bugs with IE for sure.
To your other point, I never claimed anyone was stupid. I tried to simply explain the inner working of the complex caching logic that Apollo uses. Nothing I said in my comment was incorrect. People are getting angry because I'm simply explaining the system to them. I didn't write the system, I'm just explaining that this is the INTENDED behavior from the Apollo client. The correctness of their intentions is up for debate, but the facts I stated in my comment are not.
Facts:
refetchQueries
only updates fetches with a cached network policyPeople are excited about this comment here: https://github.com/apollographql/apollo-client/issues/3633#issuecomment-597851963. But it's quite literally the concepts I previously explained.
OK, refetchQueries
fixed. Below is a sample of what I updated in my case, and steps that could help you identify what you need to update in your particular case.
// This change helped in my case. Please use the below steps to identify what you
// need to change in your case.
const variables = {
first,
- sortBy: [{ key, dir }], // removed
+ sortBy: { key, dir }, // added
};
Troubleshooting steps for your situation:
Make sure you provide the absolute same variables both to the original and to the refetch query as outlined in other posts above.
If (1) did not solve it, then you need to reveal what inconsistency you may have between your variables and how your data is stored in Apollo's cache, because Apollo converts your variables into a JSON string and makes it a part of the key at which your data is stored in its cache:
A. Familiarize yourself with Apollo's Making all other cache updates, specifically the update
method.
B. Make sure to include your original variables in the 'update' method in every place you are using the original query used to get data. This stackoverflow answer was helpful.
C. Try mutating your data while using the update
method. In my case it immediately threw an error, which revealed the solution:
Invariant Violation: Can't find field books({"first":10,"sortBy":[{"dir":"ASC","key":"NAME"}]}) on object {
... // Other data
"books({\"first\":10,\"sortBy\":{\"dir\":\"ASC\",\"key\":\"NAME\"}})": {
"type": "id",
"generated": true,
"id": "$ROOT_QUERY.books({\"first\":10,\"sortBy\":{\"dir\":\"ASC\",\"key\":\"NAME\"}})",
"typename": "BookConnection"
},
... // Other data
}.
Notice the data structure difference between these 2 lines:
"books({\"first\":10,\"sortBy\":{\"dir\":\"ASC\",\"key\":\"NAME\"}})"
books({"first":10,"sortBy":[{"dir":"ASC","key":"NAME"}]}) // Array with an object
As soon as I eliminated that difference in the original variables, the refetchQueries
began to update the UI as expected.
I have been having the same issue. I have spent 4 days debugging this but to no avail. The Network shows correct data, meaning the mutation is running and the refetch query is running and the correct data is coming in. However the UI is not rerendering to reflect it. I am now considering completely dumping Apollo 3.0 which has gone from Beta to official and making GraphQL queries with simply Axios or Fetch. Such a large buggy unwieldy bunch of functionality is like a prior day dinasaur reincarnated. Apollo says we need caching and so forth, yes but before that our more important need is that simple things like RefetchQueries work out of the box. Currently this thread shows, even after the release of Apollo3.0 official, they dont work. A huge amount of time is wasted on finagling a feature that should just work to work. And if it still doesnt work, the whole library has to be dumped. God knows by this thread so many people have tried to get it to work for so long. This after noon I am going to implement simple access to Graphql API using fetch or axios and bypass this whole mess.
I have been having the same issue. I have spent 4 days debugging this but to no avail...
Can see your frustration. I could recommend trying a fix per my post above. In particular, the part that helps you reveal a possible miss-match between your variables and the keys in the cache.
I have been having the same issue. I have spent 4 days debugging this but to no avail....
This also took me a long time to figure out, but as long as you call it with the same variables then it will work. It can be super frustrating but I don't think thats a reason to ditch apollo-client, it has a lot of other amazing features.
Thanks for the response @Ruslan @Johnny. However, please note the following
points:
1) The query that is being refetched is a simple list of items after a
delete mutation has run. There are no variables. If there are no variables
being passed to the query where is the question of there being same or
different variables.
2) I have even done an update method to evict the deleted item from the
local cache. The item is deleted from the local cache, however the query is
not refetched.
3) In my network requests, the refetched data shows correctly, with the
deleted item removed. I see 2 network requests, the first to delete and
item and the 2nd to show the revised list minus the deleted item, however
the UI does not update
So the refetch is working at the network request level, but it is most
strangely not updating the UI.
I have been stuck on this for many days. I am at a loss. Dont know what to
do further.
Best regards,
arjuna
On Wed, Jul 22, 2020 at 8:57 AM Johnny Bell notifications@github.com
wrote:
I have been having the same issue. I have spent 4 days debugging this but
to no avail....This also took me a long time to figure out, but as long as you call it
with the same variables then it will work. It can be super frustrating but
I don't think thats a reason to ditch apollo-client, it has a lot of other
amazing features.—
You are receiving this because you commented.
Reply to this email directly, view it on GitHub
https://github.com/apollographql/apollo-client/issues/3633#issuecomment-662220206,
or unsubscribe
https://github.com/notifications/unsubscribe-auth/AEVWN4TDPM22WG5VW3SZK63R4ZMBNANCNFSM4FHRUBMQ
.
@brahmaforces I think the issue is clear now. In my past experience with Apollo Client delete
mutations indeed could not (and were not meant to) be reconciled in cache declaratively. If you wanted the UI to update without refetching data on a delete mutation, you had to update the cache imperatively, using the writeQuery
method.
I'm not aware of the very latest details there and you may need to make sure you are using the right docs for the version of the client you are using, but this link may be helpful as a starting point: https://www.apollographql.com/docs/react/caching/cache-interaction/
Addition: if you are willing to refetch the list on mutation like you described above, an alternative quick fix could be to abandon the use of UI cache for this query by setting fetchPolicy: 'network-only'
on your original query.
Look like I have a specific case. For some clearence, I have student and teacher. Student should send some answer, then teacher should view list of answers. I fetch the time when student send answer and refetchQuery calls in case when there is already done one request, it works fine. But the problem when I completed mutation, then query shows old data. I'm using chromnium. It looks like that fetching a little old data. It works only if you run it on the first time. But if it run and has a cache, it means that you have no data in component and if it calls, it will return old data
I had the same problem. There is definitely a bug in refetch queries. I
have tried everything. The network shows the correct data. The cache shows
the correct data. But the ui renders old data.
Best regards,
arjuna
On Thu, Aug 6, 2020 at 8:27 PM Sabit Rakhim notifications@github.com
wrote:
Look like I have a specific case. For some clearence, I have student and
teacher. Student should send some answer, then teacher should view list of
answers. I fetch the time when student send answer and refetchQuery calls
in case when there is already done one request, it works fine. But the
problem when I completed mutation, then query shows old data. I'm using
chromnium. It looks like that fetching a little old data.—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/apollographql/apollo-client/issues/3633#issuecomment-669980144,
or unsubscribe
https://github.com/notifications/unsubscribe-auth/AEVWN4RS7FDH2YULOP7JIFTR7LAELANCNFSM4FHRUBMQ
.
using AC3 and refetch() didn't tirgger update for me. waooo sad ..... :/
ok, 2020 here is my work around guys, instead of using
refetch()
OR
refetch(DEFAULT_VARIABLES)
lets call fetchMore since fetchMore is working correctly, so we can pass the initial default variables, yeah sounds funny.
fetchMore({
variables: DEFAULT_VARIABLES
})
thanks :smile:
The thing that fixed it for me was changing the fetchPolicy
on the awaiting component. So that it didn't default to using the cache
const { data, error } = useGetProductsQuery({
fetchPolicy: 'cache-and-network'
});
Most helpful comment
Nobody from from apollo team cares
On Tue, Sep 4, 2018, 8:38 PM sandorvasas notifications@github.com wrote: