0

I'm a newbie to integrating react + ruby and was wondering if there is a way to access my sessions contents that I stored?

For example, in my app.rb, I'm storing sessions[:return_url]=blah.com. I'm currently using reactjs for my UI and want to access this return_url upon a button click. Is there a way to access it?

I've tried doing <%= return_url = sesssions[:return_url] %> but this doesn't work because I'm in a .jsx file and it can't interpret this haha (it was worth a shot)

Any tips would be appreciated!

Tim
  • 2,221
  • 6
  • 22
  • 43
  • you can't read the rails session from the client as per my understanding, but you might be able to do it through Ajax request – max pleaner Jun 19 '17 at 18:25

1 Answers1

2

If you want to read session related non-sensitive data on the client side, you can set a cookie from the server and read it using javascript on the client side.

You can set cookies with Sinatra as detailed here: http://www.sinatrarb.com/contrib/cookies

And you can read cookies with Javascript as detailed here: Read a javascript cookie by name

An alternative would be to render javascript on the server-side and store the value in a javascript variable. I believe you already tried this:

<%= return_url = sesssions[:return_url] %>`

But that is only setting a Ruby local variable, which is lost on the client side, maybe you want set that return_url as the href of the button you want to have clicked?

But, if you needed the variable inside a javascript click handler, just render a javascript variable in your ERB view:

var returnUrl = "<%= sessions[:return_url] %>";

With the above you should be access to the javascript variable returnUrl in a button click handler provided it's in the same or higher lexical scope.

DiegoSalazar
  • 13,361
  • 2
  • 38
  • 55