Starlet9334

Starlet9334

Reactivity in hologram or, why do my buttons don't do anything

Hello there,

I am trying to understand reactivity in hologram.

I’ve create a simple component calculator.ex that I am calling like this <Calculator cid="calculator" value="20" />

This is my component definition:

defmodule Calculator do
  use Hologram.Component

  prop :value, :integer

  def template do
    ~HOLO"""
    <button class="btn" $click="plus">Plus</button>
    <button class="btn" $click="minus">Minus</button>

    <p>The value is {@value}</p>
    """
  end

  def init(props, component) do
    put_state(component, :value, props.value)
  end

  def action(:plus, _params, component) do
    put_state(component, :value, component.state.value + 1)
  end

  def action(:minus, _params, component) do
    put_state(component, :value, component.state.value - 1)
  end
end

However, the displayed value doesn’t change when I hit any of the buttons.

What am I doing wrong?

Marked As Solved

bartblast

bartblast

Creator of Hologram

Thank you!

There a few problems in the code:

1)
You’ve got duplicate :only option in the Plug.Static config:

plug Plug.Static,
  at: "/",
  from: :hologram_tutorial,
  gzip: not code_reloading?,
  only: HologramTutorialWeb.static_paths(),
  only: ["hologram" | HologramTutorialWeb.static_paths()]

should be:
only: ["hologram" | HologramTutorialWeb.static_paths()]

2)
You can’t use Phoenix routing-related stuff (like ~p sigil) in Hologram templates.
instead:
<link phx-track-static rel="stylesheet" href={~p"/assets/css/app.css"} />
use:
<link rel="stylesheet" href={asset_path("assets/css/app.css")} />

3)
Don’t use Phoenix CSRF tokens inside Hologram layouts.
remove:
<meta name="csrf-token" content={get_csrf_token()} />
CSRF protection is managed automatically by Hologram, you don’t have to think about it at all.

4)
You’re layout is broken, you need to use html as the root element, and nest header and footer elements inside the body element.

instead:

<head>
  <title>{@page_title}</title>
  <Hologram.UI.Runtime />
  <link rel="stylesheet" href={asset_path("assets/css/app.css")} />
</head>
<header>Header with menu</header>
<body>
  <slot />
</body>
<footer>Footer</footer>

use:

<!DOCTYPE html>
<html>
  <head>
    <title>{@page_title}</title>
    <Hologram.UI.Runtime />
    <link rel="stylesheet" href={asset_path("assets/css/app.css")} />
  </head>
  <body>
    <header>Header with menu</header>
    <slot />
    <footer>Footer</footer>
  </body>
</html>

5)
When initializing Hologram components server-side (e.g. when using the given component in a page template - since pages are always loaded from the server) you need to use init/3 instead of init/2.


For #5 the DX could be better and Hologram could allow to use init/2 in cases where there is no init/3 defined - added that to the backlog.

Also Liked

bartblast

bartblast

Creator of Hologram

Since fixing #5 alone solved everything, the repo you shared was probably different from your original code. No worries! Just want to make sure it’s clear - for you and anyone else reading this with similar issues: each of those 5 issues will cause Hologram to break in different ways, so if any are in your actual codebase, they’ll need addressing.

bartblast

bartblast

Creator of Hologram

Thanks, I’ll look at it!

Btw, this:

def init(props, component, server) do
  component = put_state(component, :value, props.value)

  {component, server}
end

Can be just this:

def init(props, component, _server) do
  put_state(component, :value, props.value)
end

you don’t have to return server struct if it’s not modified :slight_smile:

bartblast

bartblast

Creator of Hologram

I noticed that you initialized the value as a string, but you’re treating it as an integer using the plus/minus operators.

The runtime prop type validation isn’t working yet, which might be misleading you into thinking the value gets automatically converted to an integer. Is that what’s happening?

phcurado

phcurado

I could replicate the error. I just created a basic project and added the component.
If I add the init/3 function to the component, it seems to work:

  def init(props, component, server) do
    component = put_state(component, :value, props.value)

    {component, server}
  end

but with only init/2 I have the same error as @Starlet9334

Starlet9334

Starlet9334

This was the solution. I changed

def init(props, component) do
    put_state(component, :value, props.value)
  end

to

def init(props, component, _server) do
    put_state(component, :value, props.value)
  end

and the buttons now work as expected.

Thank you for the quick help, on a Sunday no less!

Where Next?

Popular in Questions Top

logicmason
Hi there, I'm working through my first release with elixir/phoenix. I've built a release with distillery and found that it crashes when I...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
gonzofish
I’m currently trying to understand how to join three tables using Ecto. All the examples I’ve seen use 2, so maybe I’m just missing somet...
New
kostonstyle
Hi all I want to have a unix time, from the current time plus 1 hour. DateTime.now + 1 hour How to get it in elixir? Thanks
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
Codball
Mix format works fine if run from the cmd. I’ve followed this to facilitate the implementation into VSC which involves downloading an ext...
New

Other popular topics Top

senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 49522 488
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New

We're in Beta

About us Mission Statement