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

Add support for unstable_data for single fetch usage #11836

Merged
merged 7 commits into from
Jul 25, 2024
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .changeset/fifty-rockets-hide.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
"@remix-run/router": minor
---

Add a new `unstable_data()` API for usage with Remix Single Fetch

- This API is not intended for direct usage in React Router SPA applications
- It is primarily intended for usage with `createStaticHandler.query()` to allow loaders/actions to return arbitrary data + `status`/`headers` without forcing the serialization of data into a `Response` instance
- This allows for more advanced serialization tactics via `unstable_dataStrategy` such as serializing via `turbo-stream` in Remix Single Fetch
- ⚠️ This removes the `status` field from `HandlerResult`
- If you need to return a specific `status` from `unstable_dataStrategy` you should instead do so via `unstable_data()`
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@
},
"filesize": {
"packages/router/dist/router.umd.min.js": {
"none": "56.4 kB"
"none": "57.1 kB"
},
"packages/react-router/dist/react-router.production.min.js": {
"none": "14.9 kB"
Expand Down
1 change: 1 addition & 0 deletions packages/router/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ export type {

export {
AbortedDeferredError,
data as unstable_data,
defer,
generatePath,
getToPathname,
Expand Down
47 changes: 44 additions & 3 deletions packages/router/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import type {
V7_FormMethod,
V7_MutationFormMethod,
AgnosticPatchRoutesOnMissFunction,
DataWithResponseInit,
} from "./utils";
import {
ErrorResponseImpl,
Expand Down Expand Up @@ -4906,7 +4907,7 @@ async function callLoaderOrAction(
async function convertHandlerResultToDataResult(
handlerResult: HandlerResult
): Promise<DataResult> {
let { result, type, status } = handlerResult;
let { result, type } = handlerResult;

if (isResponse(result)) {
let data: any;
Expand Down Expand Up @@ -4946,10 +4947,26 @@ async function convertHandlerResultToDataResult(
}

if (type === ResultType.error) {
if (isDataWithResponseInit(result)) {
if (result.data instanceof Error) {
return {
type: ResultType.error,
error: result.data,
statusCode: result.init?.status,
};
}

// Convert thrown unstable_data() to ErrorResponse instances
result = new ErrorResponseImpl(
result.init?.status || 500,
undefined,
result.data
);
}
return {
type: ResultType.error,
error: result,
statusCode: isRouteErrorResponse(result) ? result.status : status,
statusCode: isRouteErrorResponse(result) ? result.status : undefined,
};
}

Expand All @@ -4962,7 +4979,18 @@ async function convertHandlerResultToDataResult(
};
}

return { type: ResultType.data, data: result, statusCode: status };
if (isDataWithResponseInit(result)) {
return {
type: ResultType.data,
data: result.data,
statusCode: result.init?.status,
headers: result.init?.headers
? new Headers(result.init.headers)
: undefined,
};
}

return { type: ResultType.data, data: result };
}

// Support relative routing in internal redirects
Expand Down Expand Up @@ -5476,6 +5504,19 @@ function isRedirectResult(result?: DataResult): result is RedirectResult {
return (result && result.type) === ResultType.redirect;
}

export function isDataWithResponseInit(
value: any
): value is DataWithResponseInit<unknown> {
return (
typeof value === "object" &&
value != null &&
"type" in value &&
"data" in value &&
"init" in value &&
value.type === "DataWithResponseInit"
);
}

export function isDeferredData(value: any): value is DeferredData {
let deferred: DeferredData = value;
return (
Expand Down
25 changes: 23 additions & 2 deletions packages/router/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,7 @@ export type DataResult =
*/
export interface HandlerResult {
type: "data" | "error";
result: unknown; // data, Error, Response, DeferredData
status?: number;
result: unknown; // data, Error, Response, DeferredData, DataWithResponseInit
}

type LowerCaseFormMethod = "get" | "post" | "put" | "patch" | "delete";
Expand Down Expand Up @@ -1375,6 +1374,28 @@ export const json: JsonFunction = (data, init = {}) => {
});
};

export class DataWithResponseInit<D> {
type: string = "DataWithResponseInit";
data: D;
init: ResponseInit | null;

constructor(data: D, init?: ResponseInit) {
this.data = data;
this.init = init || null;
}
}

/**
* Create "responses" that contain `status`/`headers` without forcing
* serialization into an actual `Response` - used by Remix single fetch
*/
export function data<D>(data: D, init?: number | ResponseInit) {
return new DataWithResponseInit(
data,
typeof init === "number" ? { status: init } : init
);
}

export interface TrackedPromise extends Promise<any> {
_tracked?: boolean;
_data?: any;
Expand Down