Skip to content

Commit

Permalink
Allow a new Apollolink to be set after ApolloClient instantiation
Browse files Browse the repository at this point in the history
Provides support for setting a new `ApolloLink` (or link chain)
after `new ApolloClient()` has been called, using a public
`ApolloClient.setLink()` method.
  • Loading branch information
hwillson authored and benjamn committed Jun 2, 2020
1 parent c76804e commit efa593d
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,9 @@
[@durchanek](https://github.com/durchanek) in [#6194](https://github.com/apollographql/apollo-client/pull/6194) and [#6279](https://github.com/apollographql/apollo-client/pull/6279) <br/>
[@hagmic](https://github.com/hagmic) in [#6328](https://github.com/apollographql/apollo-client/pull/6328)

- Apollo Client now supports setting a new `ApolloLink` (or link chain) after `new ApolloClient()` has been called, using the `ApolloClient#setLink` method. <br/>
[@hwillson](https://github.com/hwillson) in [#6193](https://github.com/apollographql/apollo-client/pull/6193)

### Bug Fixes

- `useMutation` adjustments to help avoid an infinite loop / too many renders issue, caused by unintentionally modifying the `useState` based mutation result directly. <br/>
Expand Down
7 changes: 7 additions & 0 deletions src/ApolloClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -553,4 +553,11 @@ export class ApolloClient<TCacheShape> implements DataProxy {
public setLocalStateFragmentMatcher(fragmentMatcher: FragmentMatcher) {
this.localState.setFragmentMatcher(fragmentMatcher);
}

/**
* Define a new ApolloLink (or link chain) that Apollo Client will use.
*/
public setLink(newLink: ApolloLink) {
this.link = this.queryManager.link = newLink;
}
}
29 changes: 29 additions & 0 deletions src/__tests__/ApolloClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2301,4 +2301,33 @@ describe('ApolloClient', () => {
expect((client.cache as any).data.data).toEqual({});
});
});

describe('setLink', () => {
it('should override default link with newly set link', async () => {
const client = new ApolloClient({
cache: new InMemoryCache()
});
expect(client.link).toBeDefined();

const newLink = new ApolloLink(operation => {
return new Observable(observer => {
observer.next({
data: {
widgets: [
{ name: 'Widget 1'},
{ name: 'Widget 2' }
]
}
});
observer.complete();
});
});

client.setLink(newLink);

const { data } = await client.query({ query: gql`{ widgets }` });
expect(data.widgets).toBeDefined();
expect(data.widgets.length).toBe(2);
});
});
});

0 comments on commit efa593d

Please sign in to comment.