Sometimes we need to retrieve data from a server when an app is being initialized. In this section, we will learn how to do just that. So far in this chapter, we have been passing Cmd.none to the init property in main to indicate that we don’t want to run any commands during initialization.
Let’s change that. We will be iterating on the same app we built in the last few sections. The good news is we have already extracted the logic for creating a command out to httpCommand in DecodingJson.elm.
All that is left to do is replace Cmd.none with httpCommand in init.
Run elm-reactor from the beginning-elm directory in terminal if it’s not running already and go to this URL in your browser: http://localhost:8000/elm-examples/DecodingJson.elm. Don’t click the Get data from server button yet. Just wait for two seconds and you should see the posts.
By passing a command to init, we’re telling the Elm Runtime to fetch posts when the app is being initialized. But we missed something along the way. The text Loading... has disappeared again. That’s because we’re initializing the posts field in our model with NotAsked instead of Loading. Let’s fix that.
If you still don’t see the loading text, make sure the json-server command is run with the --delay option.
Click the Get data from server button to make sure that it’s still working. Let’s rename that button’s title to Refresh posts to reflect its new purpose.
While we are at it, let’s also rename httpCommand to fetchPostsCommand.
Don’t forget to replace httpCommand with fetchPostsCommand in init and update functions. We should also rename the messages.
Now replace the old message names. SendHttpRequest should now be FetchPosts in the view and update functions, and DataReceived should now be PostsReceived in the fetchPostsCommand and update functions.
In this section, we learned how to run a command when an app is being initialized. In the next section, we’ll reorganize our code by splitting it into smaller modules. Here is the entire code from DecodingJson.elm thus far: