diegomura / react-pdf

📄 Create PDF files using React
https://react-pdf.org
MIT License
14.64k stars 1.16k forks source link

Fetching data from an API using a Data primitive #1523

Open radhasatam opened 2 years ago

radhasatam commented 2 years ago

We're building a reporting engine using react-pdf. The JSX templates can be:

We were trying to fetch data from within the report template using a hook or custom component but found that the report renders before the data is fetched.

Current Behaviour:

The data is fetched (console logged) but the report is already rendered because react-pdf won't wait for this async request to be fetched. Repl Share Link

Proposed Solution:

Creating a primitive type called Data or something similar which accepts a url and options param and makes a fetch request. This would be included as a step in the rendering process after the "Fetching Assets" step. It would then render the child components, similar to the dynamic content rendering in View / Text.

<Data 
    url={url} 
    options={options}
    render={(data) => <Text>{data.id}</Text>} 
 />

Additionally and possibly we could also nest the Data components in order to fetch data for sub-reports.

<Data
    url={url}
    options={options}
    render={data => <Data url={url} options={{...options, ...data}} />
}

Thoughts?

esdrasjnr commented 2 years ago

I'm also in a similar situation in my project, and it seems to be a great idea. I believe that a hook-like interface would be very nice too, something like this:

const responseData = useFetch(asyncFetcher, fallbackData);