Drab: how can I pass a value for next request

is there anyway to do something like put_session or assigns(conn, :key, value) in drab, defhandler?

  defhandler shorten_url(socket, sender) do
    long_url = sender.params["long_url_textarea"]
    user_id = socket.assigns.current_user_id
    order_id = socket.assigns.order_id
    long_url = String.trim(long_url)
    case Analytics.create_short_link(long_url) do
      {:ok, results} ->
        # Create bitly struct
        %{id: bitlink_id, link: bitlink_url, long_url: long_url} = results
        {:ok, bitly} = Bitly.create_bitly(%{bitlink_id: bitlink_id, bitlink_url: bitlink_url, long_url: long_url, total_clicks: 0, user_id: user_id, order_id: order_id})

        poke socket, shorten_url: bitlink_url, long_url: long_url, bitlink_id: bitly.id
      {:error, errors} ->
        set_prop socket, "#long-url-error", innerHTML: "Something wrong found in your url. Make sure including http://, for example http://www.example.com"
    end
  end

in this code, {:ok, bitly} = Bitly.create_bitly(%{bitlink_id: bitlink_id, bitlink_url: bitlink_url, long_url: long_url, total_clicks: 0, user_id: user_id, order_id: order_id})

I want to do something like put_session(conn, :bitly_id, bitly.id) to get a bitly id in next page.
is there anyway to do something likeput_session or assigns(conn, :key, value) in drab, defhandler?
any solution?

Thanks!

In Drab, the plug session is read-only (so far, but it might change).

The solution for your issue is to use the store. This is a Drab’s equivalent to Plug’s session.

put_store(socket, :bitly_id, bitly.id)
2 Likes

Thanks!
But I have one more question.
How can I read the value in controller that saved using put_store?
There is no socket in controller.

get_store(socket, :bitly_id)

You can’t. Store is saved in the local storage of the browser, and during page render there is no access to it. If you want to pass something back to Phoenix, the most obvious way is to use form (and <hidden>), URL or even a cookie.

There is a possibility that in 0.10 Drab will allow you to modify the session cookie (so effectively it will be put_session/2).

But, what do you want to archive? Maybe it is X/Y problem?

2 Likes

You can’t. Store is saved in the local storage of the browser, and during page render there is no access to it. If you want to pass something back to Phoenix, the most obvious way is to use form (and ), URL or even a cookie.

Yes That was first solution I tried. But hidden field is included in the same form, So it cleans up every form field when drab poke.

In this case you may use the cookie.

Still, what do you want to archive? Maybe it is X/Y problem?

1 Like