Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter a Signal on page load

Tags:

elm

For the sake of learning, I'm trying to load content only when I click on a button. So far I've managed to :

  • Reload the content when I click the button.
  • And Filter the Signal when I click (if the String I send is not "GETPERF")

But my problem is that the Ajax call is still triggered once the page loads.

Here's the code:

-- SIGNALS & MAILBOX

inbox : Signal.Mailbox String
inbox =
  Signal.mailbox "SOME TEXT"

result : Signal.Mailbox String
result =
  Signal.mailbox ""

--  VIEW

view : String -> Html
view msg  =
  div [] [
    h1 [] [text "Mailbox3"],
    p [] [text msg],
    button
      [onClick inbox.address "GETPERF"]
      [text "click perf"],
 ]

main : Signal Html
main =
  Signal.map view result.signal

-- TASK & EFFECTS

port fetchReadme : Signal (Task Http.Error ())
port fetchReadme =
  inbox.signal
    |> Signal.filter (\sig -> sig == "GETPERF" ) "boo"
    |> Signal.map (\_ -> Http.getString "http://localhost:3000/dates" `andThen` report)


report : String -> Task x ()
report html =
  Signal.send result.address html

Is there any way to prevent the first Ajax call on page load ? (Or some more idiomatic way of doing all this ?)

like image 402
charlysisto Avatar asked Dec 31 '25 02:12

charlysisto


1 Answers

The reason you're getting an initial ajax request is that Signal.filter is still keeping that initial value of "boo" (See the Signal.filter documentation here). That value is ignored in the next Signal.map statement by your use of the underscore parameter, but the Http Task is still getting returned and that's why you see an initial ajax request on page load.

Instead of using Signal.filter, you could write a conditional that only sends the ajax request in the correct circumstances, when sig is "GETPERF". And if sig is not "GETPERF" (as in page load), you can, in essence, do nothing by returning Task.succeed (). Here is a refactored fetchReadme function with these changes:

port fetchReadme : Signal (Task Http.Error ())
port fetchReadme =
  let
    fetchAndReport sig =
      if sig == "GETPERF" then
        Http.getString "http://localhost:3000/dates"
          `andThen` report
      else
        Task.succeed ()
  in
    Signal.map fetchAndReport inbox.signal
like image 122
Chad Gilbert Avatar answered Jan 06 '26 15:01

Chad Gilbert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!