Change global state from a child component

I was wondering what would be the preferred way to change global state from a child component using TEA.

In my usage example, it displays global loading indicatorwhile any json request is being executed.

A google search leads me in this article , but not 100% is the best solution. Any other suggestions?


A bit more background:

I have a SPA with various components and a Loader component. The loader component must handle transitions between views.

For example, let's say I have 3 views: (A) Information about the control panel (B) (C).

When the user is turned on (A) and clicks on the transaction, I want to (A) send a notification to the loader that he needs to load the transaction resource, and one of them has updated the location of the browser so that the root component can handle routing.

When loading a resource, the bootloader should display a loading bar at the top of the page. After that, it will update the location panel, so the root component can handle routing.

In essence, I try to avoid displaying the page (C) before loading the resource for this.

+4
source share
1 answer

Perhaps a structure like the one below may help you.

Read more about Elm scaling here (highly recommended)

.

-. , .

.

type alias Model = 
  { accounts: List Account
  , transactions: Transactions
  , currentPage : Page
  , message : String
  }

type Transactions = Idle | Loading | GotEm (List Transaction)

type Page = DashboardPage | AccountsPage | TransactionsPage

type Msg = ShowDashboard | ShowAccounts | ShowTransactions | GotJSONData

update msg model = 
  case msg of
    ShowTransactions ->
      case model.transactions of
        GotEm transactions ->
          { model 
          | currentPage = TransactionsPage 
          , message = ""
          } ! []

        Idle ->
          { model 
          | currentPage = DashboardPage
          | transactions = Loading
          , message = "Loading transactions" 
          } ! [ API.getTransactions model GotJSONData ]

        Loading ->
          model ! []

    GotJSONData transactions ->
      { model 
      | transactions = GotEm transactions 
      , message = ""
      , currentPage = TransactionsPage
      }

view model =
  case model.currentPage of
    DashboardPage ->
      DashboardPage.view model

-- DASHBOARD module

view model =
  div []
    [ ...
    , button [ onClick ShowTransactions ] [ text "Show transactions"]
    ]
0

Source: https://habr.com/ru/post/1655930/


All Articles