How call multiple endpoint when the page is rendered?

Hi guys, I’m learning Elm with the purpose to rebuild a personal project using Elm. actually I’m trying to figure out how to use multiples calls from api using Elm.

here is an example:
I have a home page and in it have two tables and a cards section.
the table one is populated with items from endpoint_1
the table two are populated with items from endpoint_2
and the cards are populated with items from endpoint_3

what I’m trying to understand is how can I call N endpoint on load action.

I’m very begginer in Elm so I just know the basic of http. I know that I can call the endpoints in init or using onclick. but has a better way to do what I mentioned?

Hi, and welcome to Elm. :slight_smile:

You can use Cmd.batch to combine multiple commands into one. So instead of e.g. single GET request like here:

init : () -> ( Model, Cmd Msg )
init _ =
    ( ...
    , Http.get { url = ..., expect = ... }

you can include several GET requests at once:

init : () -> ( Model, Cmd Msg )
init _ =
    ( ...
    , Cmd.batch
        [ Http.get { url = ..., expect = ... }
        , Http.get { url = ..., expect = ... }
        , Http.get { url = ..., expect = ... }

Note that these are not executed in the given order, but could be completed at any order.

Thank you @malaire

A question, if my project has routes, for example, home/ products/ product-detail/

even the endpoints for products and product details would be in Cmd.batch or in this case is it applied in another way?

Sorry for the question, I’m just trying to figure out all process.

If you have several routes, then for each route you should only request data that route needs, and not everything.

How exactly that is done would depend on how your program manages the routes.

Hey @dhelbegor,

Here’s a complete Ellie example that shows how you could use Cmd.batch with multiple API endpoints on page load:

Hope this helps!

I suggest you also use the RemoteData library from the start. Rationale here.

That makes it much easier to deal with issues like loading and errors.

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.