#Using fetch API in loader with defer

1 messages · Page 1 of 1 (latest)

marsh lake
#

Is it possible to use the fetch API in loader function and resolving the request by using defer with <Await> and accessing the response data of the body in component.

As defer docs say, that it serialized the awaited response to a json object, I guess it is not possible as not json serializable fields are removed... So I am losing the ability to use the fetch API in my loader functions and I may need to use some third party library for making requests... Is this correct?

The application is running with cloudflare pages, so I think it is not possible to use third party libs, because they do mostly use XMLHttpRequest (as axio) which is not supported by cloudflare workers/pages...

Here is a simple code example:

export const loader = async (args: DataFunctionArgs) => {
    const response = fetch(`some/api/request`);
    return defer({ response });
};

export default function WaitForData() {
    const data = useLoaderData();

    return (
        <Suspense fallback={<div className="loading" />}>
            <Await resolve={data.response}>
                <ShowData />
            </Await>
        </Suspense>
    );
}

export function ShowData() {
    const response = useAsyncValue();
    const [data, setData] = useState();

    useEffect(() => {
        // trying to resolve the body of the request
        const resolve = async () => {
            // json() method is not on response object
            const data = await response.json();
            setData(data)
        };
        void resolve();
    })
    
    return <>...</>
}

Thanks for any help

graceful patio