I want to enable users to download their latest invoice as PDF when they click on a button.
My Rails API is sending PDF file data like so:
def invoice
pdf_html = ActionController::Base.new.render_to_string(template: 'invoices/show')
pdf = WickedPdf.new.pdf_from_string(pdf_html)
send_data pdf, filename: 'file.pdf'
end
My React frontend requests it like so:
axios.request({
url: "http://localhost:3001/invoice",
responseType: 'blob'
}).then(response => {
console.log("invoice response:", response);
}).then(blob => {
const data = URL.createObjectURL(blob);
this.setState({ invoicePDFlink: data });
}).catch(error => {
console.log("invoice error:", error);
});
This implementation is based on an answer I found here: Using JS to consume a Rails send_data response
If I run it, the API call throws the following error: TypeError: Failed to execute 'createObjectURL' on 'URL': Overload resolution failed.
I have since learned that createObjectURL
is deprecated. I have found answers for workarounds using Mediastream but I haven't found any alternative for Blobs.
How can I solve this?
EDIT
I solved it myself. Solution below.