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

use React.use where available #10758

Merged
merged 4 commits into from
Apr 13, 2023
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/smooth-forks-shop.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@apollo/client': patch
---

use `React.use` where available
2 changes: 1 addition & 1 deletion config/bundlesize.ts
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
@@ -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;
}
};