Skip to content

Instantly share code, notes, and snippets.

@nicoespeon
Last active December 4, 2016 16:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nicoespeon/fd1e20bef77c94f7863d4c6c7907a9d4 to your computer and use it in GitHub Desktop.
Save nicoespeon/fd1e20bef77c94f7863d4c6c7907a9d4 to your computer and use it in GitHub Desktop.
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