Skip to content

Commit

Permalink
use React.use where available (#10758)
Browse files Browse the repository at this point in the history
* use `React.use` where available

* bumps bundlesize to 34.83KB (was 34.82KB)

---------

Co-authored-by: Lenz Weber-Tronic <lenz@apollographql.com>
Co-authored-by: Alessia Bellisario <alessia@apollographql.com>
  • Loading branch information
3 people committed Apr 13, 2023
1 parent aaec09c commit 9def742
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 16 deletions.
5 changes: 5 additions & 0 deletions .changeset/smooth-forks-shop.md
@@ -0,0 +1,5 @@
---
'@apollo/client': patch
---

use `React.use` where available
2 changes: 1 addition & 1 deletion config/bundlesize.ts
Expand Up @@ -3,7 +3,7 @@ import { join } from "path";
import { gzipSync } from "zlib";
import bytes from "bytes";

const gzipBundleByteLengthLimit = bytes("34.82KB");
const gzipBundleByteLengthLimit = bytes("34.83KB");
const minFile = join("dist", "apollo-client.min.cjs");
const minPath = join(__dirname, "..", minFile);
const gzipByteLen = gzipSync(readFileSync(minPath)).byteLength;
Expand Down
37 changes: 22 additions & 15 deletions src/react/hooks/internal/__use.ts
@@ -1,19 +1,26 @@
import { wrapPromiseWithState } from '../../../utilities';
import React from 'react';

// TODO: Replace the use of this with React's use once its available. For now,
// this mimics its functionality for promises by adding
// properties to the promise instance and reading them synchronously. This is
// named with two underscores to allow this hook to evade typical rules of
type Use = <T>(promise: Promise<T>) => T;
// Prevent webpack from complaining about our feature detection of the
// use property of the React namespace, which is expected not
// to exist when using current stable versions, and that's fine.
const useKey = 'use' as keyof typeof React;
const realHook = React[useKey] as Use | undefined;

// This is named with two underscores to allow this hook to evade typical rules of
// hooks (i.e. it can be used conditionally)
export function __use<TValue>(promise: Promise<TValue>) {
const statefulPromise = wrapPromiseWithState(promise);
export const __use =
realHook ||
function __use<TValue>(promise: Promise<TValue>) {
const statefulPromise = wrapPromiseWithState(promise);

switch (statefulPromise.status) {
case 'pending':
throw statefulPromise;
case 'rejected':
throw statefulPromise.reason;
case 'fulfilled':
return statefulPromise.value;
}
}
switch (statefulPromise.status) {
case 'pending':
throw statefulPromise;
case 'rejected':
throw statefulPromise.reason;
case 'fulfilled':
return statefulPromise.value;
}
};

0 comments on commit 9def742

Please sign in to comment.