Soundcheck.Check.Refactor.ExpensiveMountWork (soundcheck v0.1.0)

Copy Markdown View Source

Basics

This check is disabled by default.

Learn how to enable it via .credo.exs.

This check has a base priority of normal and works with any version of Elixir.

Explanation

Flags database and HTTP calls in a LiveView's mount/3 outside a connected?(socket) branch. mount/3 runs twice per page load, once for the disconnected HTTP render and once when the socket connects, so the query or request runs twice.

Before:

def mount(_params, _session, socket) do
  {:ok, assign(socket, :posts, Repo.all(Post))}
end

After:

def mount(_params, _session, socket) do
  {:ok, assign_async(socket, :posts, fn -> {:ok, %{posts: Repo.all(Post)}} end)}
end

Calls inside closures (assign_async/3, start_async/3) and inside if connected?(socket) do not count. Modules match expensive_modules (atoms or regexes on the alias-expanded name). Pages that must render the data on the first, disconnected response (for search engines) load it in both mounts on purpose; leave this check off for them.

Confidence: medium. Tier: syntactic (works without compiling).

Check-Specific Parameters

Use the following parameters to configure this check:

:excluded_paths

Paths to skip (atoms, binaries as path segments, or regexes).

This parameter defaults to [~r/\/test\//, "test"].

:strict

Unused.

This parameter defaults to false.

:expensive_modules

Modules whose calls count as expensive: atoms or regexes.

This parameter defaults to [~r/\.Repo$/, ~r/^(Req|Finch|HTTPoison|Tesla)$/].

General Parameters

Like with all checks, general params can be applied.

Parameters can be configured via the .credo.exs config file.