Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement reactive variables for tracking local state. #5799

Merged
merged 2 commits into from
Jan 17, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,17 @@
- Removed `apollo-boost` since Apollo Client 3.0 provides a boost like getting started experience out of the box. <br/>
[@hwillson](https://github.com/hwillson) in [#5217](https://github.com/apollographql/apollo-client/pull/5217)

- `InMemoryCache` provides a new API for storing local state that can be easily updated by external code:
```ts
const lv = cache.makeLocalVar(123)
console.log(lv()) // 123
console.log(lv(lv() + 1)) // 124
console.log(lv()) // 124
lv("asdf") // TS type error
```
These local variables are _reactive_ in the sense that updating their values invalidates any previously cached query results that depended on the old values. <br/>
[@benjamn](https://github.com/benjamn) in [#5799](https://github.com/apollographql/apollo-client/pull/5799)

- The `queryManager` property of `ApolloClient` instances is now marked as
`private`, paving the way for a more aggressive redesign of its API.

Expand Down
107 changes: 107 additions & 0 deletions src/cache/inmemory/__tests__/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1324,3 +1324,110 @@ describe("InMemoryCache#broadcastWatches", function () {
]);
});
});

describe("cache.makeLocalVar", () => {
function makeCacheAndVar(resultCaching: boolean) {
const cache: InMemoryCache = new InMemoryCache({
resultCaching,
typePolicies: {
Person: {
fields: {
name() {
return nameVar();
},
},
},
},
});

const nameVar = cache.makeLocalVar("Ben");

const query = gql`
query {
onCall {
name
}
}
`;

cache.writeQuery({
query,
data: {
onCall: {
__typename: "Person",
},
},
});

return {
cache,
nameVar,
query,
};
}

it("should work with resultCaching enabled (default)", () => {
const { cache, nameVar, query } = makeCacheAndVar(true);

const result1 = cache.readQuery({ query });
expect(result1).toEqual({
onCall: {
__typename: "Person",
name: "Ben",
},
});

// No change before updating the nameVar.
expect(cache.readQuery({ query })).toBe(result1);

expect(nameVar()).toBe("Ben");
expect(nameVar("Hugh")).toBe("Hugh");

const result2 = cache.readQuery({ query });
expect(result2).not.toBe(result1);
expect(result2).toEqual({
onCall: {
__typename: "Person",
name: "Hugh",
},
});

expect(nameVar()).toBe("Hugh");
expect(nameVar("James")).toBe("James");

expect(cache.readQuery({ query })).toEqual({
onCall: {
__typename: "Person",
name: "James",
},
});
});

it("should work with resultCaching disabled (unusual)", () => {
const { cache, nameVar, query } = makeCacheAndVar(false);

const result1 = cache.readQuery({ query });
expect(result1).toEqual({
onCall: {
__typename: "Person",
name: "Ben",
},
});

const result2 = cache.readQuery({ query });
// Without resultCaching, equivalent results will not be ===.
expect(result2).not.toBe(result1);
expect(result2).toEqual(result1);

expect(nameVar()).toBe("Ben");
expect(nameVar("Hugh")).toBe("Hugh");

const result3 = cache.readQuery({ query });
expect(result3).toEqual({
onCall: {
__typename: "Person",
name: "Hugh",
},
});
});
});
19 changes: 18 additions & 1 deletion src/cache/inmemory/inMemoryCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import './fixPolyfills';

import { DocumentNode } from 'graphql';
import { wrap } from 'optimism';
import { dep, wrap } from 'optimism';

import { ApolloCache, Transaction } from '../core/cache';
import { Cache } from '../core/types/Cache';
Expand Down Expand Up @@ -298,4 +298,21 @@ export class InMemoryCache extends ApolloCache<NormalizedCacheObject> {
}),
);
}

public makeLocalVar<T>(value: T): LocalVar<T> {
return function LocalVar(newValue) {
if (arguments.length > 0) {
if (value !== newValue) {
value = newValue;
localVarDep.dirty(LocalVar);
}
} else {
localVarDep(LocalVar);
}
return value;
};
}
Comment on lines +302 to +314
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm pretty proud of how short this implementation can be, thanks to our existing dependency tracking machinery.

}

const localVarDep = dep<LocalVar<any>>();
export type LocalVar<T> = (newValue?: T) => T;