Bertrand
Bertrand

Reputation: 1816

Run Apollo query only on React component mount (without queryData and lifecycle)

I'm using Apollo extensively in a fairly big React app I'm building, and I've found myself facing the same limitation several times.

I want to perform a query only on component mount, so that a change of this component sub-route will no re-trigger the query. I also really want to keep the container pattern, where I declare my query in the container, wrap my component and forget about it, so that my component itself remains clean of any Apollo stuff. So far, I've been able to do that by making my own Apollo high-order component that takes a component, a query and its options and returns a new component that will automatically run queryData on componentDidMount. Here's the code. I then use it this way: apolloQueryHOC(MyComponent, queryOptions);

But on a new component I've started implementing paging, and this approach simply doesn't work/becomes way too ugly for the complex paging logic I've implemented. The thing is, it works like a charm when I use the basic Apollo container approach. But it runs on every route/prop change.

So my question is, is there a way to run a "container" query only on mount, other than using withApollo and such?

Upvotes: 3

Views: 1278

Answers (1)

Bertrand
Bertrand

Reputation: 1816

Ah, the problem was actually that I was handling auth in a middleware, so my query had '' as token, and the token was fetched from indexedDB and added to the query in the middleware, overriding ''. So the query result stored in Apollo store (with the proper token as a param) was never matching the query with '' as token, resulting in Apollo querying again and again from the server.

Upvotes: 2

Related Questions