• This repository has been archived on 10/Jul/2019
  • Stars
    star
    1,405
  • Rank 33,478 (Top 0.7 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 7 years ago
  • Updated almost 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

✨ Manage your application's state with Apollo!

apollo-link-state

⚠️ WARNING ⚠️

Apollo Client 2.5 is going to be released very shortly, and will include integrated local state handling capabilities. The functionality offered by apollo-link-state will be included in the Apollo Client core, which means this project/repository will be deprecated. For those interested in trying out the new integrated local state features of AC, see apollographql/apollo-client#4155 (the changes are currently available via apollo-client@alpha and react-apollo@alpha). We're still in alpha, but will be cutting over to beta soon (so if you have any feedback, please add your comments in apollographql/apollo-client#4155). Thanks!

Manage your local data with Apollo Client!

Docs | Announcement Post | Tutorial Video by Sara Vieira

Managing remote data from an external API is simple with Apollo Client, but where do we put all of our data that doesn't fit in that category? Nearly all apps need some way to centralize client-side data from user interactions and device APIs.

In the past, Apollo users stored their application's local data in a separate Redux or MobX store. With apollo-link-state, you no longer have to maintain a second store for local state. You can instead use the Apollo Client cache as your single source of truth that holds all of your local data alongside your remote data. To access or update your local state, you use GraphQL queries and mutations just like you would for data from a server.

When you use Apollo Client to manage your local state, you get all of the same benefits you know and love like caching and offline persistence without having to set these features up yourself. 🎉 On top of that, you also benefit from the Apollo DevTools for debugging and visibility into your store.

Quick start

To get started, install apollo-link-state from npm:

npm install apollo-link-state --save

The rest of the instructions assume that you have already set up Apollo Client in your application. After you install the package, you can create your state link by calling withClientState and passing in a resolver map. A resolver map describes how to retrieve and update your local data.

Let's look at an example where we're using a GraphQL mutation to update whether our network is connected with a boolean flag:

import { withClientState } from 'apollo-link-state';

// This is the same cache you pass into new ApolloClient
const cache = new InMemoryCache(...);

const stateLink = withClientState({
  cache,
  resolvers: {
    Mutation: {
      updateNetworkStatus: (_, { isConnected }, { cache }) => {
        const data = {
          networkStatus: {
            __typename: 'NetworkStatus',
            isConnected
          },
        };
        cache.writeData({ data });
        return null
      },
    },
  }
});

To hook up your state link to Apollo Client, add it to the other links in your Apollo Link chain. Your state link should be near the end of the chain, so that other links like apollo-link-error can also deal with local state requests. However, it should go before HttpLink so local queries and mutations are intercepted before they hit the network. It should also go before apollo-link-persisted-queries if you are using persisted queries. Then, pass your link chain to the Apollo Client constructor.

const client = new ApolloClient({
  cache,
  link: ApolloLink.from([
    stateLink,
    new HttpLink()
  ]),
});

How do we differentiate a request for local data from a request that hits our server? In our query or mutation, we specify which fields are client-only with a @client directive. This tells our network stack to retrieve or update the data in the cache with our resolver map that we passed into our state link.

const UPDATE_NETWORK_STATUS = gql`
  mutation updateNetworkStatus($isConnected: Boolean) {
    updateNetworkStatus(isConnected: $isConnected) @client
  }
`;

To fire off the mutation from your component, bind your mutation to your component via your favorite Apollo view layer integration just like you normally would. Here's what this would look like for React:

const WrappedComponent = graphql(UPDATE_NETWORK_STATUS, {
  props: ({ mutate }) => ({
    updateNetworkStatus: isConnected => mutate({ variables: { isConnected } }),
  }),
})(NetworkStatus);

What if we want to access our network status data from another component? Since we don't know whether our UPDATE_NETWORK_STATUS mutation will fire before we try to access the data, we should guard against undefined values by providing a default state as part of the state link initialization:

const stateLink = withClientState({
  cache,
  resolvers: {
    Mutation: {
      /* same as above */
    },
  },
  defaults: {
    networkStatus: {
      __typename: 'NetworkStatus',
      isConnected: true,
    }
  },
});

This is the same as calling writeData yourself with an initial value:

// Same as passing defaults above
cache.writeData({
  networkStatus: {
    __typename: 'NetworkStatus',
    isConnected: true,
  }
});

How do we query the networkStatus from our component? Similar to mutations, just use a query and the @client directive! With Apollo Link, we can combine data sources, including your remote data, in one query.

In this example, the articles field will either hit the cache or fetch from our GraphQL endpoint, depending on our fetch policy. Since networkStatus is marked with @client, we know that this is local data, so it will resolve from the cache.

const GET_ARTICLES = gql`
  query {
    networkStatus @client {
      isConnected
    }
    articles {
      id
      title
    }
  }
`;

To retrieve the data in your component, bind your query to your component via your favorite Apollo view layer integration just like you normally would. In this case, we'll use React as an example. React Apollo will attach both your remote and local data to props.data while tracking both loading and error states. Once the query returns a result, your component will update reactively. Updates to Apollo Client state via apollo-link-state will also automatically update any components using that data in a query.

const WrappedComponent = graphql(GET_ARTICLES, {
  props: ({ data: { networkStatus, articles, loading, error } }) => {
    if (loading) {
      return { loading };
    }

    if (error) {
      return { error };
    }

    return {
      loading,
      networkStatus,
      articles,
    };
  },
})(Articles);

For more detailed examples, plus in-depth explanations of resolvers, defaults, and more, please check out our official docs page.

With Apollo Boost

If you are using apollo-boost, it already includes apollo-link-state underneath the hood for you. Instead of passing the link property when instantiating Apollo Client, you pass in clientState.

import ApolloClient from 'apollo-boost';

const client = new ApolloClient({
  clientState: {
    defaults: {
      isConnected: true
    },
    resolvers: {
      Mutation: {
        updateNetworkStatus: (_, { isConnected }, { cache }) => {
          cache.writeData({ data: { isConnected }});
          return null;
        }
      }
    }
  }
});

Local Development

If you're setting up for local development, and you want to integrate a local branch of apollo-link-state into another application, remember that this project is a Lerna monorepo: ./packages/apollo-link-state

To link this in, do:

cd packages/apollo-link-state && yarn link

And in your development application do:

yarn link apollo-link-state

Finally, each time you make a change in apollo-link-state, you need to run:

yarn build && yarn bundle

Now you should be good to go!

More Repositories

1

apollo-client

🚀  A fully-featured, production ready caching GraphQL client for every UI framework and GraphQL server.
TypeScript
19,300
star
2

apollo-server

🌍  Spec-compliant and production ready JavaScript GraphQL server that lets you develop in a schema-first way. Built for Express, Connect, Hapi, Koa, and more.
TypeScript
13,522
star
3

react-apollo

♻️ React integration for Apollo Client
JavaScript
6,887
star
4

apollo-ios

📱  A strongly-typed, caching GraphQL client for iOS, written in Swift.
Swift
3,737
star
5

apollo-kotlin

🤖  A strongly-typed, caching GraphQL client for the JVM, Android, and Kotlin multiplatform.
Kotlin
3,382
star
6

apollo-tooling

✏️ Apollo CLI for client tooling (Mostly replaced by Rover)
TypeScript
3,042
star
7

apollo

🚀 Open source tools for GraphQL. Central repo for discussion.
JavaScript
2,626
star
8

graphql-tag

A JavaScript template literal tag that parses GraphQL queries
TypeScript
2,275
star
9

graphql-subscriptions

📰 A small module that implements GraphQL subscriptions for Node.js
TypeScript
1,567
star
10

subscriptions-transport-ws

🔃 A WebSocket client + server for GraphQL subscriptions
TypeScript
1,524
star
11

apollo-client-devtools

Apollo Client browser developer tools.
TypeScript
1,481
star
12

apollo-link

🔗 Interface for fetching and modifying control flow of GraphQL requests
TypeScript
1,438
star
13

apollo-cache-persist

🎏 Simple persistence for all Apollo Cache implementations
TypeScript
1,368
star
14

fullstack-tutorial

🚀 The Apollo platform tutorial app
TypeScript
1,233
star
15

eslint-plugin-graphql

🚦 Check your GraphQL query strings against a schema.
JavaScript
1,194
star
16

router

A configurable, high-performance routing runtime for Apollo Federation 🚀
Rust
793
star
17

apollo-link-rest

Use existing REST endpoints with GraphQL
TypeScript
783
star
18

federation

🌐  Build and scale a single data graph across multiple services with Apollo's federation gateway.
TypeScript
659
star
19

apollo-fetch

🐶 Lightweight GraphQL client that supports middleware and afterware
TypeScript
576
star
20

apollo-rs

Spec compliant GraphQL Tools in Rust.
Rust
566
star
21

reason-apollo

Reason binding for Apollo Client and React Apollo
Reason
552
star
22

federation-demo

Federation 2 supersedes this demo and this example is no longer the newest. See https://www.apollographql.com/docs/federation/ for migration steps!
JavaScript
502
star
23

ac3-state-management-examples

✨ Learn Apollo Client 3's state management best practices
TypeScript
493
star
24

apollo-tracing

A GraphQL extension for performance tracing
475
star
25

apollo-client-nextjs

Apollo Client support for the Next.js App Router
TypeScript
446
star
26

persistgraphql

A build tool for GraphQL projects.
TypeScript
424
star
27

rover

The CLI for Apollo GraphOS
Rust
404
star
28

gatsby-theme-apollo

💜 Themes that we use to build Gatsby sites at Apollo
JavaScript
371
star
29

apollo-link-persisted-queries

Persisted Query support with Apollo Link
TypeScript
307
star
30

xcode-graphql

🛠 Xcode add-ons that add syntax highlighting for GraphQL query document files
Shell
276
star
31

apollo-studio-community

🎡  GraphQL developer portal featuring an IDE (Apollo Explorer), auto-documentation, metrics reporting, and more. This repo is for issues, feature requests, and preview docs. 📬
249
star
32

federation-jvm

JVM support for Apollo Federation
Java
247
star
33

supergraph-demo-fed2

🍿 Supergraph demo for Federation 2 and Apollo Router
Shell
162
star
34

principled-graphql

📈 Best practices for implementing and scaling a data graph
JavaScript
148
star
35

apollo-cache-control

A GraphQL extension for cache control
146
star
36

supergraph-demo

🍿 Compose subgraphs into a Federation v1 supergraph at build-time with static composition to power a federated graph router at runtime.
Shell
135
star
37

apollo-feature-requests

🧑‍🚀 Apollo Client Feature Requests | (no 🐛 please).
130
star
38

spotify-showcase

A Spotify clone that showcases the Apollo GraphQL platform.
TypeScript
126
star
39

meteor-integration

🚀 meteor add apollo
JavaScript
108
star
40

frontpage-ios-app

📄 Apollo "hello world" app, for iOS
Swift
101
star
41

space-kit

👩‍🚀 Home base for Apollo's design system: https://space-kit.netlify.com
TypeScript
88
star
42

apollo-scalajs

Use Apollo GraphQL from Scala.js apps!
Scala
88
star
43

invariant-packages

Packages for working with invariant(condition, message) assertions
TypeScript
88
star
44

apollo-federation-subgraph-compatibility

A repo to test subgraph libraries compatibility with the Apollo Federation Specification
TypeScript
77
star
45

starwars-server

JavaScript
73
star
46

blog

📝 Blog website built with Wordpress and Gatsby
JavaScript
68
star
47

iOSTutorial

The tutorial application for the Apollo iOS SDK
Swift
68
star
48

odyssey-lift-off-part1

JavaScript
64
star
49

federation-jvm-spring-example

Apollo Federation JVM example implementation using Spring for GraphQL
Java
64
star
50

vscode-graphql

Apollo GraphQL VS Code extension
TypeScript
55
star
51

apollo-kotlin-tutorial

The code for the Apollo Kotlin Tutorial
Kotlin
52
star
52

docs-examples

Example code supporting the Apollo docs
TypeScript
50
star
53

docs

📚 Apollo's docs framework
MDX
42
star
54

apollo-kotlin-2-tutorial

The code for the Apollo Android Tutorial
Kotlin
38
star
55

iOSCodegenTemplate

A template for the code you need to set up to get Swift Scripting up and running.
Swift
38
star
56

datasource-rest

A caching data source for REST APIs
TypeScript
37
star
57

apollo-workbench-vscode

Apollo Workbench is a design tool that facilitates planning changes to your supergraph. It enables you to understand the overall composition and execution of any given query at design time.
TypeScript
37
star
58

apollo-utils

Monorepo of common utilities related to Apollo and GraphQL
TypeScript
35
star
59

graphql-testing-library

Testing utilities that encourage good practices for apps built with GraphQL.
TypeScript
35
star
60

federation-rs

Contains source code for Apollo Federation's Rust<--> JavaScript interop
Rust
34
star
61

react-apollo-error-template

Apollo Client issue reproduction.
JavaScript
33
star
62

embeddable-explorer

TypeScript
32
star
63

federation-migration-example

🚀Example app migrated from schema stitching to Apollo federation
JavaScript
32
star
64

odyssey-lift-off-part5-server

Odyssey Lift-off V - Server - Course Companion App
JavaScript
31
star
65

odyssey-lift-off-part5-client

Odyssey Lift-off V - Client - Course Companion App
JavaScript
28
star
66

GraphiQL-Subscriptions-Fetcher

GraphiQL's fetcher that supports GraphQL-Subscriptions with the `subscriptions-transport-ws` package
TypeScript
28
star
67

supergraph-demo-k8s-graph-ops

Archived: GitOps config repo for an Apollo GraphQL federated graph with a supergraph router and subgraph services deployed to Kubernetes.
Shell
28
star
68

apollo-ios-dev

Apollo iOS Development Repo
Swift
28
star
69

apollo-ios-pagination

Swift
26
star
70

odyssey-lift-off-part2

Odyssey Lift-off Part 2 Course Companion App
JavaScript
26
star
71

spacex

A re-creation of https://github.com/SpaceXLand/api
TypeScript
21
star
72

apollo-graphql-stream-scenes

This is used for hosting streaming scenes for OBS - for Apollo GraphQL stream
JavaScript
19
star
73

federation-next

Moved to the Router repository
Rust
19
star
74

subgraph-template-typescript-apollo-server-boilerplate

A template for a minimal setup Apollo Server 4.x using TypeScript
TypeScript
17
star
75

federation-hotchocolate

HotChocolate support for Apollo Federation
C#
16
star
76

odyssey-lift-off-part3

Odyssey Lift-off Part 3 Course Companion App
JavaScript
15
star
77

odyssey-voyage-I

JavaScript
14
star
78

typescript-repo-template

A template for TypeScript projects with pre-configured tooling
TypeScript
14
star
79

subgraph-template-typescript-apollo-server

A Typescript template for Apollo Server as a subgraph using Apollo Federation
TypeScript
13
star
80

next-apollo-example

Template for creating Apollo Client + Next.js reproductions
JavaScript
13
star
81

community

Apollo community guidelines
JavaScript
13
star
82

design-principles

Where we are defining and collaborating on our Apollo internal design principles (individually and collaboratively). This is a public repo, but intended only for use by Apollo employees.
13
star
83

odyssey-lift-off-part4

Odyssey Lift-off Part 4 Course Companion App
JavaScript
12
star
84

core-schema-js

Typescript library for processing core schemas
TypeScript
12
star
85

apollo-client-swift-playground

Swift
11
star
86

apollo-ios-codegen

Apollo iOS Code Generation
Swift
11
star
87

test-span

Rust
11
star
88

specs

Apollo Library of Technical Specifications
CSS
10
star
89

router-template

A general purpose self-hosted Apollo Router template connected to GraphOS
Dockerfile
10
star
90

apollo-midnight

A VS Code color theme based on Apollo Studio Explorer color palette.
9
star
91

serde_json_bytes

a JSON Value object with strings backed by Bytes, parsed by serde_json
Rust
8
star
92

hack-the-supergraph

JavaScript
8
star
93

subgraph-template-rust-async-graphql

A boilerplate template project for building a subgraph with async-graphql
Rust
8
star
94

router-biscuit-plugin

⚠️experimental⚠️ plugin for the router using Biscuit tokens for authorization
Rust
7
star
95

devhub

🔭 Explore all the latest resources for building apps with Apollo
JavaScript
7
star
96

client-router-e2e-tests

Apollo Client ↔️ Router E2E Test Suite
JavaScript
7
star
97

odyssey-lift-off-lab

Odyssey Lift-off Lab starter repo
JavaScript
7
star
98

graphchat

TypeScript
6
star
99

introspector-gadget

GraphQL introspection utilities
Rust
6
star
100

zen-observable-ts

Thin wrapper around zen-observable and @types/zen-observable, to support ESM exports
JavaScript
6
star