Created
August 20, 2021 08:26
-
-
Save vasco3/0509a5db123b3f9f04e97635b830b97f to your computer and use it in GitHub Desktop.
CSV Rescript recipe
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let csvAtom = Recoil.atom({key: "csvAtom", default: Belt.Map.String.empty}) | |
let headers = ( | |
`codigo`, | |
`descripcion`, | |
`cantidad requerida`, | |
) | |
module CsvButton = { | |
type makeCsvData = {fields: array<string>, data: array<array<string>>} | |
@module("papaparse") @val external makeCsv: makeCsvData => string = "unparse" | |
@send external setAttribute: (Dom.element, string, string) => unit = "setAttribute" | |
@send external click: Dom.element => unit = "click" | |
let (_h0, h1, h2, h3,) = headers | |
@react.component | |
let make = (~title) => { | |
let aEl = React.useRef(Js.Nullable.null) | |
let csvData = Recoil.useRecoilValue(csvAtom) | |
<> | |
<button | |
className="ml-4 button-blue" | |
type_="button" | |
onClick={_ => { | |
let values = csvData->Belt.Map.String.valuesToArray | |
let csv = makeCsv({ | |
fields: [h0, h1, h2, h3, ], | |
data: values, | |
}) | |
aEl.current | |
->Js.Nullable.toOption | |
->Belt.Option.forEach(el => { | |
el->setAttribute( | |
"href", | |
`data:text/plain;charset=utf-8,${Js.Global.encodeURIComponent(csv)}`, | |
) | |
el->setAttribute("download", `${title}.csv`) | |
el->click | |
}) | |
}}> | |
{`CSV`->React.string} | |
</button> | |
<a ref={ReactDOM.Ref.domRef(aEl)} className="w-1" /> | |
</> | |
} | |
} | |
module Component = { | |
@react.component | |
let make = (~component: component, ~model, ~quantity ) => { | |
let setCsv = Recoil.useSetRecoilState(csvAtom) | |
React.useEffect4(() => { | |
setCsv(map => | |
map->Belt.Map.String.set( | |
component.reference, | |
[ | |
component.reference, | |
component.description, | |
quantity->formatNumber, | |
], | |
) | |
) | |
None | |
}, (component.reference, quantity, t)) | |
// ... <table> | |
} | |
module Component = { | |
@react.component | |
let make = (~component: component, ~model, ~quantity ) => { | |
<div> | |
<CsvButton title="..."/> | |
<Component /> | |
<Component /> | |
<Component /> | |
</div> | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment