atkayla
atkayla

Reputation: 8849

How to refetch a query from a different component without a mutation?

Say I have some component with a query that fetches something:

   <Query query={GET_THING}>
            {({ loading, error, data, refetch }) => {
                if (loading) return <Text>Loading...</Text>;
                if (error) return <Text>Error :(</Text>;

                // currently am just storing refetch in global var
                globalRefetches.thing = refetch;
                // external component can call globalRefetches.thing()

                return <Text>{data.getThing}</Text>;
            }}
   />

Then I navigate to a Filters screen where I can set some filters to adjust the result.

Is there a clean way for me to refetch the query on the previous screen? Currently, I am just storing them in a global var, but I would imagine there is some way to pull the query out of the store and refetch it with new variables?

Upvotes: 0

Views: 2290

Answers (2)

Cory McAboy
Cory McAboy

Reputation: 332

There are a number of approaches to fix this, but I think Apollo's intended solution is to update the cache with the new filter/sort criteria using the ApolloConsumer component. The ApolloConsumer component gives you direct access to your cache. You can read and write directly to it. You can also build your own resolvers, which is a great way to modularize your cache operations, such as filter and sort. Unfortunately, there is a bit of a learning curve when interacting with the cache and the documentation could be a bit better. For the most part, you would be altering the cache using the readQuery, writeQuery, readFragment, and WriteFragment functions among a few others.

I hope this helps!

Upvotes: 1

xadm
xadm

Reputation: 8418

You need some kind of global state manager - when sth is changed in store (filter options) all connected components (observing this) are updated. You can use redux, mobx ... there is a lot of simple, small, light, easy solution to choose from - or build sth own with context api.

Apollo client has support for local state management - not easiest one but similiar to normal graphql usage.

Upvotes: 0

Related Questions