kiliman / remix-typedjson

This package is a replacement for superjson to use in your Remix app. It handles a subset of types that `superjson` supports, but is faster and smaller.
MIT License
435 stars 19 forks source link

`useTypedFetcher`'s `data` can be `undefined` #31

Open nickluger opened 11 months ago

nickluger commented 11 months ago

Maybe I got something wrong, but the data property returned by useTypedFetcher can be undefined. TS does not complain, while the runtime code fails.

const { data }  = useTypedFetcher<typeof loader>;
console.log(data.foo); // error thrown, Cannot read properties of undefined etc.

Taking a look at the implementation:

export type TypedFetcherWithComponents<T> = Omit<FetcherWithComponents<T>, 'data'> & {
    data: UseDataFunctionReturn<T>; 

// ==> should be 

export type TypedFetcherWithComponents<T> = Omit<FetcherWithComponents<T>, 'data'> & {
    data: UseDataFunctionReturn<T> | undefined; // add undefined here
};

Workaround

import type { FetcherWithComponents } from "@remix-run/react";
import type { UseDataFunctionReturn } from "remix-typedjson";
import { useTypedFetcher as useTypedFetcherOriginal } from "remix-typedjson";

export function useTypedFetcher<T>(): Omit<FetcherWithComponents<T>, "data"> & {
  data: UseDataFunctionReturn<T> | undefined;
} {
  return useTypedFetcherOriginal<T>();
}