diff --git a/CHANGELOG.md b/CHANGELOG.md index 55dc17080f5..3e95d6a1730 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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)
[@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.
+ [@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.
diff --git a/src/ApolloClient.ts b/src/ApolloClient.ts index 736db198415..709bca67651 100644 --- a/src/ApolloClient.ts +++ b/src/ApolloClient.ts @@ -553,4 +553,11 @@ export class ApolloClient 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; + } } diff --git a/src/__tests__/ApolloClient.ts b/src/__tests__/ApolloClient.ts index 44ce8ff0c10..d1ad5e409a7 100644 --- a/src/__tests__/ApolloClient.ts +++ b/src/__tests__/ApolloClient.ts @@ -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); + }); + }); });