Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Blog - How I implemented a download button with Cycle.js - ExportToCsv driver
import R from 'ramda';
// Export a driver to be used in our Cycle.js app.
// It takes an `input$` stream that contains `data` to be download.
function exportToCSVDriver(input$) {
// `data` should be formatted as an Array of Arrays (= lines of CSV).
// -> `[["name1", "city1", "other info"], ["name2", "city2", "more info"]]`
input$.subscribe((data) => {
// Parse data to create a CSV file.
// See: http://stackoverflow.com/questions/14964035/how-to-export-javascript-array-info-to-csv-on-client-side
let csvContent = 'data:text/csv;charset=utf-8,';
data.forEach((infoArray, index) => {
const dataString = infoArray.join(',');
csvContent += index < data.length ? `${dataString}\n` : dataString;
});
// Create a link in the page to trigger the download.
const link = document.createElement('a');
link.setAttribute('href', encodeURI(csvContent));
// Name the CSV file based on data attributes.
// Implementation is based on TKAT specificities (https://github.com/nicoespeon/trello-kanban-analysis-tool).
// This part can be refactor to open-source the driver.
const head = R.head(data);
link.setAttribute('download', `cfd-from-${head[1]}-to-${R.last(head)}.csv`);
// Required for Firefox.
document.body.appendChild(link);
// Download the data file.
link.click();
});
}
export { exportToCSVDriver };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.