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

LegitStack
I’m hoping you guys can give me some general advice and perhaps code examples if you’re feeling up to it. I’m very interested in Elixir,...
New
Kagamiiiii
Student &amp; New to elixir. Nice language. I want to convert a english character, e.g. “a”, which is stored in a variable, to it’s asci...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
makeitrein
Hey all, just started picking up Elixir last week and am writing a scraper as a learning project. Baby step #1 is extracting the number ...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
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
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New

Other popular topics Top

shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
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
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 35421 110
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
beno
I will often find my self writing things similar to: case some_value do nil -&gt; something() "" -&gt; something() _ -&gt; someth...
New

We're in Beta

About us Mission Statement