Search code examples
elixirphoenix-frameworkphoenix-live-view

JS.__struct__/1 is undefined, cannot expand struct JS


I try to walk through an JS example of the LiveView 0.17.1 docs (https://hexdocs.pm/phoenix_live_view/0.17.1/Phoenix.LiveView.JS.html)

So I created a new Phoenix 1.6.2 application with mix phx.new demo3 --no-ecto and changed the mix.exs deps part to this:

  defp deps do
    [
      {:phoenix, "~> 1.6.2"},
      {:phoenix_html, "~> 3.0"},
      {:phoenix_live_reload, "~> 1.2", only: :dev},
      {:phoenix_live_view, "~> 0.17.1"},
      {:floki, ">= 0.30.0", only: :test},
      {:phoenix_live_dashboard, "~> 0.5"},
      {:esbuild, "~> 0.2", runtime: Mix.env() == :dev},
      {:swoosh, "~> 1.3"},
      {:telemetry_metrics, "~> 0.6"},
      {:telemetry_poller, "~> 1.0"},
      {:gettext, "~> 0.18"},
      {:jason, "~> 1.2"},
      {:plug_cowboy, "~> 2.5"}
    ]
  end

After that I created a LiveView page and added this example code to it:

  def hide_modal(js \\ %JS{}) do
    js
    |> JS.hide(transition: "fade-out", to: "#modal")
    |> JS.hide(transition: "fade-out-scale", to: "#modal-content")
  end

Starting the server fails:

$ mix phx.server
Compiling 1 file (.ex)

== Compilation error in file lib/demo3_web/live/stock_watch_live.ex ==
** (CompileError) lib/demo3_web/live/stock_watch_live.ex:66: JS.__struct__/1 is undefined, cannot expand struct JS. Make sure the struct name is correct. If the struct name exists and is correct but it still cannot be found, you likely have cyclic module usage in your code
    lib/demo3_web/live/stock_watch_live.ex:66: (module)

What do I have to add/change to fix this?


Solution

  • Adding alias Phoenix.LiveView.JS on top of the file solves the problem. Thanks to @scott-thompson!

    The docs have just been updated. https://github.com/phoenixframework/phoenix_live_view/commit/a0b39649ce6f02561033fd42c7205644fe3a706b#diff-a095f1aa9c79bb58142c5628142a5ddc52bb344547400409a8c6a3237896cedc