react-apollo icon indicating copy to clipboard operation
react-apollo copied to clipboard

How to trigger query refetch from another component?

Open Peterabsolon opened this issue 9 years ago • 36 comments

What is the best practice for triggering query refetch from another component / page?

I have two pages - list and form - and I want the list to update when I submit the form.

How can I do that?

Peterabsolon avatar Mar 23 '17 14:03 Peterabsolon

Sometimes I really suck at being a React developer :(

Peterabsolon avatar Mar 23 '17 15:03 Peterabsolon

Why did you close this? Which solution did you go with? I'm very interested to find out if there is a common best practice for this since I think it's a very normal use case. Thanks.

cuttlas avatar Apr 16 '17 20:04 cuttlas

Please provide a solution. It'd be very helpful.

karloluis avatar May 16 '17 16:05 karloluis

What's the design pattern to actually achieve this? Anyone can point in the right direction please? 👍

saimeunt avatar May 29 '17 22:05 saimeunt

Have you guys read the docs here? http://dev.apollodata.com/react/cache-updates.html

Probably the easiest is to use the refetchQueries option.

stubailo avatar May 29 '17 22:05 stubailo

Also covered in the tutorial here: https://dev-blog.apollodata.com/react-graphql-tutorial-mutations-764d7ec23c15

stubailo avatar May 29 '17 22:05 stubailo

I think this problem is not really an issue when doing a mutation. I only encounter this problem when I want to update other queries based on the result of a query.

arvinsim avatar Jan 24 '18 09:01 arvinsim

I think the issue is that the component firing the refetch is different than the component rendering the data

webberwang avatar May 23 '18 04:05 webberwang

Hi, I have this problem too, @webberwang , you're right!! The issue is refetch from another component that render the data.

Example: Component A do some query fetch. Component B is a button that trigger mutation and refetch query fetch.

I've tried format like this mutate({ mutation: xxxxx, variables: { ...values }, refetchQueries: yyyy })

The refetchQueries are triggered successfully, but, the component A are not rerendering, networkstatus , loading are still same. Tried notifyOnNetworkStatusChange: true options , but not helping

charlielukman avatar May 23 '18 05:05 charlielukman

I've encountered the same issue. I can confirm that the issue is that the component firing the mutation (and refetchQuery) is different from the component rendering the data - just as @charlielukman described.

The apollo cache is updated just fine by the refetchQuery.

The two components share the same parent component, but even forcing an update of the parent component (calling this.forceUpdate() or changing its state) does not cause component rendering the data to update.

Did anyone find a solution for this scenario?

dybzon avatar Jun 16 '18 07:06 dybzon

Having the same problem as @dybzon

waclock avatar Jun 19 '18 03:06 waclock

It would be great if this could be re-opened as it is, I think, a very valid question. I'm facing exactly the same problem. I've a list of items displayed in one component, and a completely separate modal component that mutates one. Of course, the refetchQueries in my modal component doesn't help at all.

ghost avatar Jun 19 '18 08:06 ghost

Hi, I try another approach, which is using apollo state.

For my case : Component A doing query to fetch data, which is consume parameter from apollo state. Component B that trigger mutation, set the state.

When state change, the query in component A automatically re-trigger

It works fine for me. Hope it helps. :smiley:

charlielukman avatar Jun 19 '18 12:06 charlielukman

Interesting idea @charlielukman, I'll give that a try, thanks!

ghost avatar Jun 19 '18 13:06 ghost

Hey Team, This probably won't work for every use case however mine required that I update one component from information being submitted in a subcomponent.

Since I knew what the changes were supposed to look like and where they were supposed to go I opted to use "update" inside of the mutation to give me a space where I could utilize readQuery and writeQuery on the cache. No refetch necessary

Here's a quick example of that. In this case, removing a friend from a friend's list. the removeFriend const was then piped into a compose(...) with some other stuff.

const removeFriend = graphql(RemoveFriendMutation, {
  props: (props) => ({
    removeFriend: friend => {
      return props.mutate({
        variables: {
          friend: friend
        },
        update: (store, {resp}) => {
          const data = store.readQuery({
            query: FriendsListQuery, 
          });

          let pruned = // Some code to remove a user from data.getFriendsList.friends

          data.getFriendsList.friends = pruned;

          store.writeQuery({ 
            query: FriendsListQuery,
            variables{
                // LIST NECESSARY VARIABLES HERE. these select the related query from your cache 
            },
            data 
          });
        }
      })
    }
  })
})

jrounsav avatar Jul 18 '18 00:07 jrounsav

Maybe worth noting that in my case the "necessary variables" I mentioned were just "count: null, nextToken: null". On a page where I happen to be pulling everything.

The cache stores data by using a combination of the query and those variables, so if I had another with "count: 5" cached then I'm thinking I might run into some trouble

jrounsav avatar Jul 18 '18 00:07 jrounsav

So if my understanding of the question is correct I think I solved it (wanting to trigger refetchQueries independently of a mutation.) Try client.queryManager.refetchQueryByName(queryname) as a one liner you can use anyplace after client is called.

For example, I want my mutation update function to attempt to write the mutation results to cache but if it can't find the result or push the changes only then do a refetch on the associated query:

mutate({
       variables: mutation_vars,
       update: (cache, { data }) => {
         const mutation_data = data[mutation_type][mutation_name];
         const current_cache = cache.readQuery({
                 query: query,
                 variables: query_vars,
         });

         try {
         // Attempt to merge mutation result data into Apollo cache and rewrite to it
           current_cache.Location[0].children.push(mutation_data);
           cache.writeQuery({
                 query: query,
                 variables: query_vars,
                 data: current_cache,
                });
         }
         catch(error) {
           console.error("Mutation data not merged with Apollo cache, check pathing:\n",error);
           // In the event we can't update the cache, we can refetch associated queries so the
           // result are still added without refreshing the page.
           client.queryManager.refetchQueryByName(query_name);
         }
       }
     });

As for problems others are having updating multiple components after a mutation, using a subscription-based solution with the one liner client.queryManager.refetchQueryByName(query_name) seems like it would work.

JackGrannan avatar Jul 30 '18 14:07 JackGrannan

@arvinsim redux maybe can help you

Hocoh avatar Aug 19 '18 20:08 Hocoh

  • Updating any Query component after mutation + refetchQueries should work out of the box, no additional code is needed.
  • To refetch the query independent of the mutation, just calling client.query works for me (all Query components are updated correctly).

Hope this helps!

alamothe avatar Aug 20 '18 19:08 alamothe

Here is a nice docs about it https://www.apollographql.com/docs/react/essentials/queries.html#refetching

nemish avatar Aug 20 '18 20:08 nemish