I’m loving Elm but currently struggling to understand the elm/file package and how to use it.
Background
Martin Janiczek’s Elm ports and JavaScript solution to ‘How can I access a file on my local drive?’ works fine. I read the code, made sure I understood it, and got it working in my app, all in about an hour. But I then discovered Elm File, and decided I should be doing it purely in Elm. Too much time later (I’m embarrassed to say how long) I’m still trying.
What I’ve achieved
As I understand it, the process of File is Request Files -> Load Files -> Extract Data
.
In my implementation:
-
a user-click sends a
FilesRequested
message -
update’s
FilesRequested
branch runs
Select.files ["text/csv","text/csv"] FilesLoaded
-
update’s
FilesLoaded
branch adds the files to the model and then runs
Task.perform TextLoaded (File.toString file)
on each file
I’m calling functions from update — (model, function call)
— and starting to think this might be ‘wrong’ (?). Still learning.
Stages 2 and 3 are/were unreliable — sometimes worked sometimes didn’t.
I fixed stage 3 by recognizing that I had to ensure that the model was updated with the new file data BEFORE running the code to extract the data. The andThen
function from the brilliant elm-update-extra package came to my rescue: update model andThen
process it’s content.
I haven’t included my code because it’s long, complicated, and probably wrong/irrelevant
My misunderstandings
I have read Evan’s document Working with Files, and his File load code.
Looking at Evan’s code, it occurs to me that maybe the reason that stage 2 — loading the file(s) in — only sometimes works is because I’m not quite grabbing the file immediately but am instead going round through update.
Looking more closely, I see that Evan doesn’t use File.Select
at all, but just File.decoder
. Maybe because of the ‘Limitations’ mentioned on the File.Select page.
But this is very confusing because surely a file must be selected(/loaded) before it can be decoded. And, if Select is both unreliable and unnecessary, why does it exist at all?
Further, surely the elm/file
package contains all the necessary functions to load files and extract the content, without having to resort to Json.Decode
to unpack what elm/file
has packaged up?
As you can see, I’m lost.