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 committed Apr 25, 2020
1 parent e75a1ec commit a9d789d
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 @@ -144,6 +144,9 @@
- Add a default `gc` implementation to `ApolloCache`. <br/>
[@justinwaite](https://github.com/justinwaite) in [#5974](https://github.com/apollographql/apollo-client/pull/5974)

- 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 @@ -555,4 +555,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 @@ -2271,4 +2271,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 a9d789d

Please sign in to comment.