GraphQL client application with global router

Hello,

We are implementing a GraphQL web application with Apollo client (by Apollo elements) and a Vaadin router. I’m looking for a way do make the router globally available. Some solutions I found are a Context API, Redux etc.

Apollo contains the concept of reactive variables which is a way to make objects globally available.
Is this also meant to store more complex like a router etc.?

Thanks

It’s not impossible (and nothing will hinder you to do that), but it’s not meant for that.

If you are looking for a dependency injection mechanism, go with React Context - that’s what it is made for.

If you just need to have some kind of global and your application is only rendered in the browser and the value will never change, you could also use some kind of global variable - no need for any external mechanism.

Redux and Apollo Client are meant to hold data, not code.

1 Like

Thanks @lenz!

In the same context it’s not completely clear to me when to use:

  • reactive variables
  • local-only fields

The documentation mentions some pros and cons, but for example in the use case where we want to reference the logged in user which is global, we could:

  • use a reactive variable which is simple, but then I would use another mechanism beside my query I perform.
  • make the logged in user part of the client side schema and execute an (existing) query on it. This involves also extending the type policy etc. which seems a bit more work

Are there any pros or cons for both mechanisms? Is the choice when to use what maybe what I mention myself: when we already execute a query do it in the query as this is consistent, uses the same abstraction and otherwise use a reactive variable?

chatgtp also has some interesting answers on this: Reactive Variables vs Local-Only Field

Phew, that’s not really easy to answer.

Reactive variables can be used on their own, or be part of a local-only field. So if you use a local-only field, there’s a good chance that you’ll be using reactive variables behind the scenes.

Personally, I’d keep using Apollo Client mostly for Graphql state, and extend your schema a little bit with local-only fields.

If you don’t have a lot of additional state, you can also use “standalone” reactive vars, but as soon as you start getting into complex state outside of your Apollo Client, you’ll probably want to use a full-fledged state management library and distinguish between “api state”, held by Apollo Client and “application state”, held in your global state management solution.

Just make sure to not have data from one source leaking into the other - each data in your application should have one “source of truh”, while it is perfectly valid to mix & match that data for display in your component.