Process error regarding state

I am reading the tutorial written here:

The elixir code below returns an error:

defmodule TrackingState do
  def loop(state \\ []) do
    receive do
      {:push, item} -> state = [item | state]
      whatever -> {:error, "#{whatever} is not a valid"}
    end
    IO.inspect(state)
    loop(state)
  end
end

The error is:

warning: the variable “state” is unsafe as it has been set inside one of: case, cond, receive, if, and, or, &&, ||. Please explicitly return the variable value instead. For example:

case integer do
  1 -> atom = :one
  2 -> atom = :two
end

should be written as

atom =
  case integer do
    1 -> :one
    2 -> :two
  end

Unsafe variable found at:
Desktop/junk/test.ex:8

The error is just a warning but I would like to know how to fix it.

The warning does show how to fix it. Just replace case in warning with receive from your code and you should see some similarities.

Either way you need to think what shall happen to state when you received something invalid?

Perhaps remain unchanged? Makes no sense for me but mirrors your current code:

defmodule TrackingState do
  def loop(state \\ []) do
    state = receive do
      {:push, item} -> [item | state]
      whatever ->
        {:error, "#{whatever} is not a valid"}
        state
    end
    IO.inspect(state)
    loop(state)
  end
end
1 Like

It’s not my code , I am using others code to learn the language hence why I am not acclimated with the errors

Still the wartning has shown an example of how to fix the problem.


And why did you delete all the follow up questions? Don’t you need an answer anymore? Will you ask them again in another thread?