Apollo Client Link: a kick of the tires
Relay at work and was interested in trying out
Apollo. I find the idea of a single library to manage state and network requests very compelling. The idea is to build a simple chat interface… but like for one user.
If you’re currently implementing a client-link and are more interested in reference, then I would recommend the docs and accompanying official demo Github repo. You might be more interested in my example afterwards. I am not going to cover installation, because to be honest I can’t really remember. I’m sure if you spam enough installs things will work out for you 🙏. You can see the demo here. There is also a Github.
Step 1: set up the
In this file we provide the client with our resolvers, type definitions and data management. Resolvers manage
state , the
cache and defaults manage the data and
typeDefs give a declarative method of typing — without having to adopt Typescript or Flow.
Step 2: resolve requests
As you can see the
cache is quite flexible and feels pretty intuitive in my opinion. By including the
@client directive we tell Apollo to use a client link. It is possible to compose links which opens up interesting opportunities. I’d like to explore how the
Node interface interacts with the
cache but that’s outside the scope of our demo. We would expect that this code will only run once per
Message regardless of how many times the a
Query is made for that
Step 3: Implement the UI
As you can see Apollo provides
Mutation Components that wrap the underlying requests. The
IncomingMessages Component runs a Query to return *all* of the messages — if we extend the app this will be a good target for refactor.
renderOutgoing is a simple form that will run a Mutation to “post” a message and then reset the state of the input. The
IncomingMessages Component will re-render because of the
Mutation which is convenient because it allows us to avoid
Context in a parent Component.
Personally, I enjoyed using the
apollo-link-state library and think it offers a strong development story. You can quickly prototype a UI while building the state logic… logic that can fluidly transition into network requests.
edit: thanks to /u/stolinski for mentioning that it can be useful to write directly to the cache.