0
votes

I am having trouble with even the most basic of session operations in Phoenix. For example, if I generate the stock Phoenix (1.4) app, and the only change I make is to page_controller.ex, the index action of which now looks like:

 def index(conn, _params) do
   put_session(conn, :franch, "foo")
   text(conn, "session is: #{get_session(conn, :franch)}")
 end

when I start the server and navigate to that page, I see:

session is: 

Is there some additional configuration that I need to do in order to be able to store values in the session? The stock app fetches the session in the browser pipeline so I was assuming there's no more to do, but maybe I'm wrong?

1
conn is immutable. Try conn = put_session(conn, :franch, "foo")AbM
Duh. Thank you!Steve Rowley

1 Answers

0
votes

Since Elixir is a functional programming language, variables are immutable. Which means that you are guaranteed to have the same value before and after a method call unless you reassign the variable:

foo = "Hello"
AnyModule.anyMethod(foo) 
foo # You are guaranteed that foo still points to the value "Hello"

The only way to get the variable foo to reference some value other than what is currently assigned to it, is to reassign it:

foo = "Hello"
foo = MyModule.addThere(foo)
foo # "Hello There"

So, put_session(conn, key, value) can not modify the passed in parameter conn it instead returns a new Plug.Conn which is materially the same as the old one, except with the new key/value pair.

To get the text to display correctly you need to assign conn to the output of the method

 conn = put_session(conn, key, value)